问题描述
作为学习backbone.js 的一部分,我正在尝试从一个简单的JSON 文件中填充一个集合.但我无法让它工作.
I am trying to populate a collection from a simple JSON file as part of learning backbone.js. But I can't get it to work.
进行了 AJAX 调用(通过 FireBug 验证),但 toJSON
方法返回 undefined
.
The AJAX call is made (verified with FireBug), but the toJSON
method returns undefined
.
我做错了什么?
theModel = Backbone.Model.extend();
theCollection = Backbone.Collection.extend({
model: aModel,
url: "source.json"
});
theView = Backbone.View.extend({
el: $("#temp"),
initialize: function () {
this.collection = new theCollection();
this.collection.fetch();
this.render();
},
render : function () {
$(this.el).html( this.collection.toJSON() ); // Returns blank
}
});
var myView = new theView;
这是我的 JSON:
[{
"description": "Lorem ipsum..."
},
{
"description": "Lorem ipsum..."
}]
推荐答案
fetch
是异步的,如果您立即调用 render
,您的集合还不会被填充.要解决这个问题,您只需要将集合 reset 事件(Backbone>=1.0 的 sync 事件)绑定到视图渲染:
fetch
is asynchronous, your collection won't yet be populated if you immediately call render
. To solve this problem, you just have to bind the collection reset event (sync event for Backbone>=1.0) to the view render :
theView = Backbone.View.extend({
el: $("#temp"),
initialize: function () {
this.collection = new theCollection();
// for Backbone < 1.0
this.collection.on("reset", this.render, this);
// for Backbone >= 1.0
this.collection.on("sync", this.render, this);
this.collection.fetch();
},
render : function () {
console.log( this.collection.toJSON() );
}
});
注意 bind 方法的第三个参数,为该方法提供正确的上下文:http://documentcloud.github.com/backbone/#FAQ-this
Note the third argument of the bind method, giving the correct context to the method:http://documentcloud.github.com/backbone/#FAQ-this
这篇关于Backbone.js - 即使获取成功,数据也不会填充到集合中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!