0

我想拥有多个独特的事件总线,它们也可以监听全局事件。这是我想看到的输出:

global triggered on a by master
global triggered on b by master
search triggered on a by a
search triggered on b by b

这是我的代码:

var master = Backbone.Events;
// when this is attached a listens to b and b listens to a
// when this isn't attached no one listens to the global event
// master.on('fake', function(){});
var a = $.extend({}, master);
var b = $.extend({}, master);

function respond(bus, event, by) {
    $('#log').append('<div><code>' + event + '</code> triggered on <code>' + bus + '</code> by <code>' + by + '</code></div>');
}
a.on('global', function (by) { respond('a', 'global', by); });
b.on('global', function (by) { respond('b', 'global', by); });

a.on('search', function (by) { respond('a', 'search', by); });
b.on('search', function (by) { respond('b', 'search', by); });

master.trigger('global', 'master');
a.trigger('search', 'a');
b.trigger('search', 'b');

这是一个没有的小提琴 master.on,这是一个 master.on.

4

1 回答 1

1

发生这种情况是因为您从同一个主对象扩展,因此您在所有实例上注册事件。

我基于两个不同的渠道提出了这个解决方案:

var master = Backbone.Events;
var Bus = (function(){    
    function Bus(){
        this.vent = {};
        _.extend(this.vent, Backbone.Events);
        this.globalVent = master;
    }
    return Bus;
})();

var a = new Bus();
var b = new Bus();

function respond(bus, event, by) {
    $('#log').append('<div><code>' + event + '</code> triggered on <code>' + bus + '</code> by <code>' + by + '</code></div>');
}
a.globalVent.on('global', function (by) {
    respond('a', 'global', by);
});
b.globalVent.on('global', function (by) {
    respond('b', 'global', by);
});

a.vent.on('search', function (by) {
    respond('a', 'search', by);
});
b.vent.on('search', function (by) {
    respond('b', 'search', by);
});

master.trigger('global', 'master');
a.vent.trigger('search', 'a');
b.vent.trigger('search', 'b');

这是一个工作小提琴

于 2013-07-19T09:12:54.747 回答