我正在尝试从本地 API 填充我的 Backbone 集合并更改视图以显示数据。我的集合中的 fetch() 调用似乎成功了,并获取了数据,但 fetch 操作不会更新集合中的模型。
这是我的模型和收藏品:
var Book = Backbone.Model.extend();
var BookList = Backbone.Collection.extend({
model: Book,
url: 'http://local5/api/books',
initialize: function(){
this.fetch({
success: this.fetchSuccess,
error: this.fetchError
});
},
fetchSuccess: function (collection, response) {
console.log('Collection fetch success', response);
console.log('Collection models: ', this.models);
},
fetchError: function (collection, response) {
throw new Error("Books fetch error");
}
});
我的观点是这样的:
var BookView = Backbone.View.extend({
tagname: 'li',
initialize: function(){
_.bindAll(this, 'render');
this.model.bind('change', this.render);
},
render: function(){
this.$el.html(this.model.get('author') + ': ' + this.model.get('title'));
return this;
}
});
var BookListView = Backbone.View.extend({
el: $('body'),
initialize: function(){
_.bindAll(this, 'render');
this.collection = new BookList();
this.collection.bind('reset', this.render)
this.collection.fetch();
this.render();
},
render: function(){
console.log('BookListView.render()');
var self = this;
this.$el.append('<ul></ul>');
_(this.collection.models).each(function(item){
console.log('model: ', item)
self.appendItem(item);
}, this);
}
});
var listView = new BookListView();
我的 API 返回 JSON 数据,如下所示:
[
{
"id": "1",
"title": "Ice Station Zebra",
"author": "Alistair MacLaine"
},
{
"id": "2",
"title": "The Spy Who Came In From The Cold",
"author": "John le Carré"
}
]
当我运行这段代码时,我在控制台中得到了这个:
BookListView.render() app.js:67
Collection fetch success Array[5]
Collection models: undefined
这向我表明 fetch 调用正在获取数据,但它没有用它填充模型。谁能告诉我我在这里做错了什么?