主干集合提取数据,但不设置模型
Backbone collection fetches data, but doesn't set models
我正在尝试从本地 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 调用正在获取数据,但它没有用它填充模型。谁能告诉我我在这里做错了什么?
您的fetchSuccess
函数应该有collection.models
而不是this.models
。
console.log('Collection models: ', collection.models);
并请考虑@Pappa提出的建议。
您正在对 BookList 集合调用 fetch 两次,一次是在初始化时,另一次是在初始化 BookListView 时。在实例化集合时填充集合本身被认为是不好的做法。您还将在其初始化调用中呈现视图两次,一次是为了响应"reset"事件,然后您也直接调用它。
我建议从 BookList 集合中完全删除初始化函数,并在 BookListView 的初始化调用结束时删除对 this.render() 的调用。
相关文章:
- 显示模块模式在Knockout中设置模型的新实例
- 将输入值设置为ng模型属性[Angular]时出现问题
- 如何在ExtJs4应用程序上为视图、存储和模型设置自定义文件夹名称
- 使用“angular.copy”设置模型-what'这有好处
- 主干集合提取数据,但不设置模型
- 如何在 NodeJS 中使用续集设置模型验证
- 如何在角度中动态设置模型名称
- 如果我在 model.save 成功时设置模型会怎样?
- 在Node.js中设置模型的正确方法
- 如何在使用Ember和Ember数据设置模型属性之前编辑表单数据
- 在BackboneJS中,关于设置模型属性的说明
- 设置模型属性的内部字段
- 如何设置模型值与视图元素文本在javascript (MVC 4)
- 如何在Ember.js的控制器单元测试中设置模型数据
- 通过API数据设置模型和动态路由
- 如何在AngularJS中使用select对象数组来设置模型的值
- 使用下划线外部模板在背部骨骼中设置模型内容
- 如何设置模型's加载顺序以避免关系错误
- 在promise.then()中设置模型时,视图中的Nativescript绑定属性不会更新
- Angular数据绑定-手动设置模型的值