Javascript Backbone.js-即使获取成功,也不会在集合中填充数据

Javascript Backbone.js-即使获取成功,也不会在集合中填充数据,javascript,json,backbone.js,Javascript,Json,Backbone.js,作为learning backbone.js的一部分,我正在尝试从一个简单的JSON文件填充一个集合。但我不能让它工作 AJAX调用已经发出(通过FireBug验证),但是toJSON方法返回undefined 我做错了什么 theModel = Backbone.Model.extend(); theCollection = Backbone.Collection.extend({ model: aModel, url: "source.json" }); theView

作为learning backbone.js的一部分,我正在尝试从一个简单的JSON文件填充一个集合。但我不能让它工作

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..."
}]

我相信问题在于你的json

或者重写集合上的parse方法,以使用json

或者您可以更改json:)


我相信这就是你的json应该是什么样子,只是一个模型数组。

fetch
是异步的,如果你立即调用
render
,你的集合还不会被填充。要解决此问题,只需将集合重置事件(主干网的同步事件>=1.0)绑定到视图渲染:

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() );
   }
});
theView=Backbone.View.extend({
el:$(“临时”),
初始化:函数(){
this.collection=新的集合();
//对于主干<1.0
this.collection.on(“重置”,this.render,this);
//对于主干>=1.0
this.collection.on(“sync”,this.render,this);
this.collection.fetch();
},
渲染:函数(){
log(this.collection.toJSON());
}
});
请注意bind方法的第三个参数,它为该方法提供了正确的上下文:

你好,桑德尔。谢谢你。我在这里输入了错误的JSON,所以不幸的是它没有那么容易:)你意识到
fetch()
是异步的吗?不,我不知道。那么我应该调用
render()
作为回调吗?参见上文-用回调更改它我也很好奇。我的第一反应是绑定到集合的
reset
事件来呈现视图。我很好奇你是怎么想的……呃,你完全影响了你问题的答案。现在你有了一个
这个
问题。如果我是你,我会还原更改,原来的问题更有趣。非常感谢你回答我的问题。第三个论点对我来说是全新的。我想这与执行
uuz.bindAll(这个“render”)是一样的
或只是
\uuu.bindAll(这个)
获取所有方法中可用的
this
?大多数情况下,此语法仅将render方法绑定到重置事件中的this,而u.bindAll(this,'render')将render绑定到所有调用中的this。感谢您的解释。我现在开始了解绑定
这个
和绑定事件之间的区别:)
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() );
   }
});