我有我的模型骨幹集合視圖中添加不被稱爲與模型
var Client = Backbone.Model.extend({});
var Colony = Backbone.Collection.extend({
url: '/presence/knock',
model: Client
});
意見
var ClientView = Backbone.View.extend({
initialize: function(){
this.render();
},
template: _.template('...'),
render: function(){
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var ColonyView = Backbone.View.extend({
initialize: function(){
_.bindAll(this, 'addOne', 'addAll');
this.collection.bind('add', this.addOne);
this.collection.bind('refresh', this.addAll);
this.collection.bind('change', this.addAll);
},
addOne: function(item){
console.log('addOne', item);
var view = new ClientView({
model: item
});
$(this.el).append(view.render().el);
},
addAll: function(){
var self = this;
this.collection.each(function(item){
self.addOne(item);
});
},
render: function(){
this.addAll();
return this;
}
});
和我一起上/presence/knock
彗星更新集合。
var colony = new Colony([{
ip: '127.0.0.1',
name: 'localhost.localdomain',
lsup: 'now'
}]);
setInterval(function(){
colony.fetch({
update: true
});
}, 5*1000);
var colonyView = new ColonyView({
collection: colony
});
$("#clients-board").append(colonyView.render().el);
當colonyview呈現addOne
第一次得到一個客戶端作爲參數,因爲它通過所謂的addAll。但是當addOne
通過add
事件我在檢查item
看到所謂的下一次是不是一個client
環R {CID: 「C606」,屬性:對象,集合:R,_changing:假的,_previousAttributes:對象...}
r {cid:「c606」,attributes:Object,collection:r,_changing:false,_previousAttributes:Object ...}是一個從backbone.model擴展的模型對象。它可以是客戶端模型的一個實例。也許你可以登錄item.toJSON()來查看屬性 – nilgun
我認爲你必須編寫colony.fetch({update:true,remove:false})。如果沒有刪除,每個新模型都不會觸發「添加」事件。 http://backbonejs.org/#Collection-fetch – redconservatory
@nilgundag我在addOne中檢查了item.toJSON()它是'Object {clients:Array [1]}'這是一個殖民地(collection) –