我使用backbone.js从REST服务器获取集合。获取触发器很好并使用数据填充集合。但是,“reset”触发器永远不会被触发,因此永远不会调用addAll()。手动调用addAll()可以正常工作 - 但为什么在集合上调用fetch()时不应该“重置”触发?
以下是代码:
define(['backbone-tastypie'], function(Backbone) {
var Machine = Backbone.Model.extend({
url: function(){
return this.get('resource_uri') || this.collection.url;
}
});
return Machine;
});
define(['backbone-tastypie','models/machine'], function(Backbone, Machine) {
var Machines = Backbone.Collection.extend({
model: Machine,
url: '/api/rest/machine/',
parse: function(data){
return data.objects;
}
});
return Machines;
});
define(['underscore','backbone-tastypie'], function(_, Backbone) {
var MachineTableEntryView = Backbone.View.extend({
tagName: 'tr',
template: _.template($('#machine-row-template').html()),
render: function(){
$(this.el).html(this.template(this.model.toJSON()));
console.log('lol');
return this;
}
});
return MachineTableEntryView;
});
define(['underscore','backbone-tastypie','collections/machines','views/machine_table_entry'], function(_, Backbone, Machines, MachineTableEntryView) {
var MachineTableView = Backbone.View.extend({
el: $('#app'),
initialize: function(){
_.bindAll(this, 'addOne', 'addAll');
Machines.bind('reset', this.addAll);
this.machines = new Machines();
this.machines.fetch();
},
addAll: function(){
this.machines.each(this.addOne);
},
addOne: function(machine){
var view = new MachineTableEntryView({model:machine});
this.$('#machines').append(view.render().el);
},
});
return MachineTableView;
});
答案 0 :(得分:16)
您需要将事件侦听器绑定到您创建的集合的实例,而不是Collection构造函数:
define(['underscore','backbone-tastypie','collections/machines','views/machine_table_entry'], function(_, Backbone, Machines, MachineTableEntryView) {
var MachineTableView = Backbone.View.extend({
el: $('#app'),
initialize: function(){
_.bindAll(this, 'addOne', 'addAll');
this.machines = new Machines();
this.machines.bind('reset', this.addAll);
this.machines.fetch();
},
addAll: function(){
this.machines.each(this.addOne);
},
addOne: function(machine){
var view = new MachineTableEntryView({model:machine});
this.$('#machines').append(view.render().el);
},
});
return MachineTableView;