2013-07-18 45 views
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'); 

這裏有一個fiddle withoutmaster.on和這裏的one withmaster.on

回答

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

+0

這行之有效。謝謝 – ryan