Backbone:引用父对象的事件

时间:2012-08-26 12:48:21

标签: javascript events javascript-events backbone.js underscore.js

我想用一个父对象替换某个子对象的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.Collections或Backbone.Models,它们具有与前端相同的视图系统。

如您所见,解决方案尚未达到最佳效果。

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

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

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

1 个答案:

答案 0 :(得分: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和属性,并且可能会在下一个版本的任何时间点发生变化,因为只保证公共方法/属性不会在版本之间进行更改我相信你在这里尝试了一些过于复杂的事情,看看你所做的一些错误,你们一直在努力尝试太多不同的方式:)总是尽量保持简单