2

我想用Backbone.Events我的父对象之一替换某个子对象中的系统。例子:

// initialize function of the repository object
initialize: function() {
        var users = new Backbone.Collection();
        
        // we save a reference of our event system in ourEvents object
        var ourEvents = {};
        ourEvents.on = this.on;
        ourEvents.off = this.off;
        ourEvents.trigger = this.trigger;
        ourEvents.bind = this.bind;
        ourEvents.unbind = this.unbind;

        // now we overwrite events in users.collection with our one
        _.extend(users, ourEvents);

        // now we listen on the test event over this
        this.on('test', function() { alert('yiha'); });

        // but triggering over users works too!
        users.trigger('test');
}

正如你一样,我们现在得到了某种一对多的事件系统。一个侦听器和许多可以触发事件的对象。

这有助于我在使用不同的Backbone.CollectionsBackbone.Models与前端具有相同视图系统的情况下工作。

如您所见,解决方案还不是最优的。

是否有更短的方法来覆盖事件系统?

更新: 所以我研究了主干源代码,发现它Backbone.Events保存了一个回调列表: this._callback. 这至少在理论上应该有效:

this.users._callbacks = this._callbacks = {};
4

1 回答 1

3

Clean Backbone 这样做的方法是将事件绑定到集合上,而不是出于某种原因尝试从对象中复制它们

// initialize function of the repository object
initialize: function() {
        var users = new Backbone.Collection();

        users.on('on', this.on, this);
        users.on('off', this.off, this); // third parameter to set context of method to the current view
        // ...and so on
        // you were listening here on the current view but triggering later on collection - this would never work
        users.trigger('on'); // would call the this.on method in the context of current view
        // if this method would have been triggered from inside of the users collection it would still trigger the desired method inside of this view
}

提示 - 永远不要接触和利用前面带下划线的方法和变量 - 这些是私有 API 和属性,并且可能在下一个版本的任何时间点发生变化,因为只有公共方法/属性保证不会在发布。我相信您在这里尝试过分复杂化并查看您所犯的一些错误,您一直在尝试太努力并且以太多不同的方式:) 始终尝试使事情保持简单

于 2012-08-26T19:26:21.733 回答