Backbone.js的 - 数据没有被填充在收集即使获取成功 [英] Backbone.js - data not being populated in collection even though fetch is successful
问题描述
我想填充从一个简单的JSON文件的集合作为学习Backbone.js的一部分。但我不能得到它的工作。
在AJAX调用时(与萤火虫验证),但的toJSON
方法的返回值未定义
。
我在做什么错了?
theModel = Backbone.Model.extend();theCollection = Backbone.Collection.extend({
型号:AMODEL,
网址:source.json
});theView = Backbone.View.extend({
EL:$(#TEMP),
初始化:功能(){
this.collection =新theCollection();
this.collection.fetch();
this.render();
},
渲染:功能(){
$(this.el)的.html(this.collection.toJSON()); //返回空白
}
});MyView的VAR =新theView;
下面是我的JSON:
[{
说明:Lorem存有......
},
{
说明:Lorem存有......
}]
取
是异步的,你的收藏还不会填充如果您立即拨打渲染
。为了解决这个问题,你只需要收集绑定的重置的事件(的同步的事件骨干> = 1.0)到视图渲染:
theView = Backbone.View.extend({
EL:$(#TEMP), 初始化:功能(){
this.collection =新theCollection(); //为骨干< 1.0
this.collection.on(复位,this.render,这一点); //为骨干> = 1.0
this.collection.on(同步,this.render,这一点); this.collection.fetch();
}, 渲染:功能(){
的console.log(this.collection.toJSON());
}
});
请注意绑定方法的第三个参数,给予正确的上下文的方法:
http://documentcloud.github.com/backbone/#FAQ-this
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.
The AJAX call is made (verified with FireBug), but the toJSON
method returns undefined
.
What am I doing wrong?
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;
Here's my JSON:
[{
"description": "Lorem ipsum..."
},
{
"description": "Lorem ipsum..."
}]
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() );
}
});
Note the third argument of the bind method, giving the correct context to the method: http://documentcloud.github.com/backbone/#FAQ-this
这篇关于Backbone.js的 - 数据没有被填充在收集即使获取成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!