我的代码分三步完成:
当我用cssElementListView渲染集合时,
怎么了?
/************************************ Collection *******************************/
var cssElementList = Backbone.Collection.extend({
//on permet de charger different model de donnée
initialize: function(props) {
var self=this;
// binding definition
_.bindAll(this, "populate");
this.bind('reset', this.populate);
// get value from props
this.url=(props.url==undefined)? "model.json" : props.url;
this.elem=(props.elem==undefined)? "#age" : props.elem;
this.model=(props.model==undefined)? cssElement : props.model;
this.meta("result", "false");
//fetch with url JSON file
this.fetch();
},
populate: function(){
var self=this;
this.each(function(model){
var mid=model.get('id');
var mavaleur=$(self.elem).css(mid);
model.set("value",mavaleur);
});
},
});
/************************************ CollectionView *******************************/
//Collection View
var cssElementListView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render');
this.render();
},
render: function(){
var self=this;
//TROUBLE IS HERE
alert("toto");
this.collection.each(function(model){
var view = new cssElementView({ el: this.el, model: model });
$(this.el).append(view.render());
},this);
}
});
答案 0 :(得分:1)
我怀疑fetch()的异步特性存在问题。你的警报调用给了它足够的时间来完成从服务器获取数据,但如果你不进行调用,当你尝试渲染时,集合仍然是空的,因为fetch的ajax没有从服务器返回称其成功回调。 (您可以在第758行附近阅读代码here。)
最好将渲染绑定到重置事件(或other event),而不是在初始化视图时立即渲染,如下所示:
// in cssElementListView.initialize
this.collection.on('reset', this.render, this);