-1
Model
및 Collection
을 정의했으며 데이터베이스에 이미 레코드가 있으므로 페이지로드시 해당 레코드를 모두 표시하려고합니다.backbone.js 전체 데이터베이스 테이블로 채우기 방법
Backbone.sync
을 사용해 보았지만 Chrome 디버깅 모드에서 여전히 빈 컬렉션이 표시됩니다.
내 Backbone.js 코드 :
(나는 때문에 템플릿 종속성이 몇 가지 코드를 제거했다). 여기$(document).ready(function() {
var Item = Backbone.Model.extend({
defaults: { "date": "",
"text": "default text"
},
initialize: function() { // STEP 3
var dateString = giveMeDate();
this.set("date", dateString);
},
urlRoot : './items'
});
var ItemList = Backbone.Collection.extend({
model: Item,
url: './items/',
initialize: function() {
this.fetch();
}
});
//************ VIEW ********************************
var ItemListView1 = Backbone.View.extend({
el: 'body',
initialize: function(myitemList) {
this.itemlist = myitemList;
this.itemlist.bind('add', this.addOneItem, this);
this.render();
},
addOneItem: function() {
this.render();
},
render: function() { // STEP 5 this is called because add() is bound to this.render (in initialization of this View)
text = this.itemlist.toJSON();
string = JSON.stringify(text);
$("#view1").html('');
$.tmpl("itemTemplate", text).appendTo("#view1");
return this;
},
events: {
"keypress #new-item": "createOnEnter" // STEP 1
},
createOnEnter: function(e) {
if (e.keyCode != 13) return;
if (!$("#new-item").val()) return;
this.itemlist.create({"text": $("#new-item").val()}); // STEP 2
$("#new-item").val('');
}
});
$("#new-item").focus();
var itemlist = new ItemList();
Backbone.sync("read", itemlist);
var myitemListView = new ItemListView1(itemlist);
내가 Backbone.sync 후 컬렉션에서 볼 것입니다 :
d
_byCid: Object
_byId: Object
length: 0
models: Array[0]
__proto__: x
문제를 재현 할 수있는 최소한의 코드가 생길 때까지 최대한 많은 코드를 제거하십시오. 이 질문을하는 데 필요한 단계가 있어야합니다. – fguillen
컬렉션에 할당 한 'url'은 컬렉션의 내용을 JSON으로 반환하는 주소를 가리켜 야합니다. 백본이 나머지 부분을 처리합니다. 또한 서버와 동기화 할 때마다'Bacbone.sync'를 호출 할 필요가 없습니다. 'collection.fetch()'는 올바른 방법입니다. – jakee