我正在使用backbone.js 开发我的第一个项目。它应该是 Play 的前端!具有 JSON 接口(interface)的应用程序。这是我的 JS 代码的一部分
var api = 'http://localhost:9001/api'
// Models
var Node = Backbone.Model.extend();
// Collections
var Nodes = Backbone.Collection.extend({
model: Nodes,
url: api + '/nodes',
});
// Views NODE
var NodeView = Backbone.View.extend({
el: $("#son_node_elements"),
render: function(){
var source = $("#son_node_item_templ").html();
var template = Handlebars.compile(source);
$(this.el).append(template(this.model.toJSON()));
return this;
}
});
var NodeListView = Backbone.View.extend({
initialize: function(){
_.bindAll(this, "render");
this.collection = new Nodes();
this.collection.bind("change",this.render);
this.collection.fetch();
this.render();
},
render: function(){
_(this.collection.models).each(function(item){
var nodeView = new NodeView({model: item});
$(this.el).append(nodeView.render().el);
}, this);
}
});
Nodes = new NodeListView({el:$('#son_nodes')});
我的问题是,当调用 this.render()
时,this.collection.fetch()
仍未完成,并且 this.collection
code> 不包含任何要渲染的内容。当我在 this.render()
处设置断点(例如使用 firebug)时,一切正常,因此不会立即调用 this.render()
。当我访问本地 JSON 文件而不是我的应用程序的 api 时,我得到完全相同的结果。有什么建议如何处理这个问题吗?
最佳答案
Fetch 也可以从外部 View 调用,因此让 View 监听它:
this.collection.bind("reset",this.render);
每次调用 this.collection.fetch();
时都会触发重置事件
最后,跳过this.render();
不要自己调用它,因为重置事件处理程序会为您执行此操作。
关于javascript - Backbone.js 的延迟 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8510845/