我希望有多个独特的事件总线也可以收听全球事件。这是我想要看到的输出:
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');
答案 0 :(得分: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');
这是一个有效的fiddle