可能重复:
Backbone.js-更改名称时未触发
在我下面的函数中,控制台显示数据,但没有任何东西附加到body标记,任何人都会发现问题。。
我的json:
[
{name:'student4'},
{name:'student5'},
{name:'student6'}
]
代码:
(function($){
var model = Backbone.Model.extend({
defaults:{
name:'default name'
}
});
var collection = Backbone.Collection.extend({
model:model,
url: 'data/names.json'
});
var itemViews = Backbone.View.extend({
tagname:'li',
render:function(){
this.$el.html(this.model.get('name'));
return this;
}
})
var view = Backbone.View.extend({
el: $("#contacts"),
initialize:function(){
this.collection = new collection();
this.collection.on("reset", this.render, this);
this.collection.fetch();
},
render:function(){
var that = this;
_.each(this.collection.models, function(item){
that.renderName(item);
})
},
renderName:function(item){
var itemView = new itemViews({model:item});
this.$el.append(itemView.render().el); //nothing rendering
}
});
var stView = new view();
})(jQuery)
问题出现在这两行:
this.collection.fetch(); //it seems it's not fetching;
this.render();
Collection.fetch
是一个异步操作。当您render
视图时,请求尚未返回,因此您的集合为空。尝试将render方法绑定到集合reset
事件:
collection.on("reset", this.render, this);
this.collection.fetch();