Backbone.js - 即使获取成功,数据也没有填充到集合中
我正在尝试从一个简单的 JSON 文件填充一个集合,作为学习backbone.js 的一部分。但我无法让它发挥作用。
已进行 AJAX 调用(使用 FireBug 进行验证),但 toJSON
方法返回 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..."
}]
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..."
}]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
fetch
是异步的,如果您立即调用render
,您的集合将不会被填充。要解决这个问题,您只需将集合 reset 事件(Backbone>=1.0 的 sync 事件)绑定到视图渲染即可:注意绑定方法的第三个参数,为该方法提供正确的上下文:
http://documentcloud.github.com/backbone/#FAQ-this
fetch
is asynchronous, your collection won't yet be populated if you immediately callrender
. To solve this problem, you just have to bind the collection reset event (sync event for Backbone>=1.0) to the view render :Note the third argument of the bind method, giving the correct context to the method:
http://documentcloud.github.com/backbone/#FAQ-this
我相信问题出在你的json上,
要么你覆盖集合上的解析方法,使用你的json
,要么你可以更改json:)
我相信这就是你的json应该是什么样的,只是一个模型数组。
i believe the problem lies in your json
either you override the parse method on the collection, to work with your json
or you could change the json :)
i believe this is what your json should look like, just an array of your models.