我试图从本地API填充我的Backbone集合并更改视图以显示数据。我的集合中的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
它向我表明提取调用正在获取数据,但它没有用它填充模型。任何人都可以告诉我我在这里做错了什么?
非常感谢user10,那就是答案!我仍然在找到自己的方式,并没有意识到“this”在fetchSuccess中具有全局作用域 - 我仍然不是100%确定为什么,但是当我将“this”绑定到fetchSuccess初始化它拥有的集合时集合的范围。 –
'fetchSuccess'是Backbone.sync调用的回调函数,由Backbone.js在全局范围内执行。 – user10
Ohhhh所以这就是为什么!感谢user10。 –