骨干自定义事件触发器无法识别?

Int*_*ist 6 backbone.js

我第一次学习Backbone.js而且我遇到了一个问题,试图从触发中获取自定义事件(或者从视图中识别出它被触发时)?

您可以在此处查看我的收集代码:https://github.com/Integralist/Backbone-Playground/blob/master/Assets/Scripts/App/main.js#L72-86,初始化时会触发自定义collection:init事件.

var Contacts = Backbone.Collection.extend({
    model: Contact,

    initialize: function(){
        this.trigger('collection:init');
        this.bind('add', this.model_added, this);
    },

    model_added: function(){
        console.log('A new model has been created so trigger an event for the View to update the <select> menu');
    }
});
Run Code Online (Sandbox Code Playgroud)

但是后来在我的View中,我正在收听该事件,我无法启动该功能populate:https://github.com/Integralist/Backbone-Playground/blob/master/Assets/Scripts/App/main. JS#L90-107

var ContactsView = Backbone.View.extend({
    initialize: function(){
        console.log(contacts.models, 'get initial model data and populate the select menu?');
    },

    events: {
        'collection:init': 'populate',
        'change select': 'displaySelected'
    },

    populate: function(){
        console.log('populate the <select> with initial Model data');
    },

    displaySelected: function (event) {
        console.log('get model data and display selected user', event);
    }
});
Run Code Online (Sandbox Code Playgroud)

我有什么想法我做错了吗?

nik*_*shr 9

视图中的事件哈希用于将DOM中的事件绑定到视图,例如,由渲染视图中的元素引发的事件.要收听您的收藏集引发的事件,您必须手动设置它们:

var ContactsView = Backbone.View.extend({
    initialize: function(){
        contacts.on("collection:init",this.populate,this);
    }
    ...
});
Run Code Online (Sandbox Code Playgroud)

请注意,您正在使用全局联系人变量,我建议使用Backbone机制并将您的集合传递给构造函数,就像使用el:

var ContactsView = Backbone.View.extend({
    initialize: function(){
        console.log(this.collection.models);
        this.collection.on("collection:init",this.populate,this);
    }
    ...
});

var contacts_view = new ContactsView({
    el: $('#view-contacts'),
    collection:contacts
});
Run Code Online (Sandbox Code Playgroud)

正如@mu在评论中所说的那样,你的事件将不会做任何事情,因为你在集合的initialize方法中触发它,因此在你可以绑定视图中的任何东西之前,集合的构造函数会自动调用它.看到这个小提琴可视化呼叫顺序:http://jsfiddle.net/yRuCN/

在别处触发它,或者,如果我正确读出你的意图,你(可能)想要使用内置的重置事件:

var ContactsView = Backbone.View.extend({
    initialize: function(){
        this.collection.on("reset",this.populate,this);
    }
    ...
});
Run Code Online (Sandbox Code Playgroud)

有关潜在用途的示例,请参见http://jsfiddle.net/yRuCN/1/.