问题
I've my models
var Client = Backbone.Model.extend({});
var Colony = Backbone.Collection.extend({
url: '/presence/knock',
model: Client
});
views
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;
}
});
and I update the collection with a comet on /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);
First time when the colonyview is rendered addOne
gets a client as argument, because its called through addAll. but next time when addOne
is called through add
event I see in inspector item
is not a client
r {cid: "c606", attributes: Object, collection: r, _changing: false, _previousAttributes: Object…}
回答1:
I think i figured out your problem.
Here is a working fiddle with your code: http://jsfiddle.net/nilgundag/KbwHZ/
I have used mockjax to mock the server and here what it returns:
[{
ip: '127.0.0.1',
name: 'localhost.localdomain',
lsup: 'now'
},
{
ip: '127.0.0.2',
name: 'localhost.localdomain',
lsup: 'now'
}]
Since you said you are getting Object {clients: Array[1]}, probably your server returns:
[{
clients:[{
ip: '127.0.0.1',
name: 'localhost.localdomain',
lsup: 'now'
}]
}]
Here is fiddle which demonstrates your case: http://jsfiddle.net/nilgundag/TxZxp/
You should change your server code to only send the client array, not an object containing a property clients and the associated array.
来源:https://stackoverflow.com/questions/18964354/backbone-collection-view-add-not-being-called-with-a-model