gpt4 book ai didi

backbone.js - Backbone "reset"收集触发器未触发

转载 作者:行者123 更新时间:2023-12-04 10:05:14 25 4
gpt4 key购买 nike

我使用backbone.js 从REST 服务器获取集合。 Fetch 触发良好并用数据填充集合。但是,永远不会触发“重置”触发器,因此永远不会调用 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;
});

模型 View
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;
});

最佳答案

您需要将事件监听器绑定(bind)到您创建的集合的实例,而不是 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;

关于backbone.js - Backbone "reset"收集触发器未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8761396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com