骨干“重置”收集触发器未触发

问题描述 投票:0回答:1

我正在使用backbone.js 从REST 服务器获取集合。获取触发器正常并用数据填充集合。然而,“重置”触发器永远不会被触发,因此 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;
});
backbone.js
1个回答
16
投票

您需要将事件侦听器绑定到您创建的集合的实例,而不是集合构造函数:

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;
© www.soinside.com 2019 - 2024. All rights reserved.