独特的主干事件总线,也可以共享全局事件

Unique backbone event buses that can also share global events

本文关键字:事件 也可以 共享 全局 总线      更新时间:2023-09-26

我想要多个唯一的事件总线,它们也可以监听全局事件。以下是我希望看到的输出:

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的小提琴<em。>

之所以会发生这种情况,是因为您从同一个主对象进行扩展,因此您在所有距离上注册事件。

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

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');

这是一个工作小提琴

相关文章: