Pros / cons of the global observer object vs mixer

When creating a complex JS application, what are the pros and cons of a global observer object that fires events and which all other objects subscribe, or by mixing or prototyping the pub / helper methods on all objects that are responsible for triggering their own events?

Take, for example, a card game with trading, game, and table objects (psuedocode-ish):

// "Global" observer version

var observer = {
    // publish and subscribe methods defined here
};

dealer.deal = function(cards) {
    // performs logic for dealing cards
    observer.publish('dealer:dealt', cards, this);
};

player.play = function(cards) {
    // performs logic for which card is played
    observer.publish('player:played', cards, this);
};

table.showCards = function(cards, player) {
    // performs logic for showing cards that the dealer dealt
    // or that the player played
};

observer.subscribe('dealer:dealt', table.showCards);
observer.subscribe('player:played', table.showCards);

against

// Pub/sub mixin/prototype version

dealer.deal = function(cards) {
    // performs logic for dealing cards
    this.publish('dealt', cards);
};

player.play = function(cards) {
    // performs logic for which card is played
    this.publish('played', cards);
};

table.showCards = function(cards) {
    // performs logic for showing cards that the dealer dealt
    // or that the player played
};

dealer.subscribe('dealt', table.showCards);
player.subscribe('played', table.showCards);
+5
source share
1 answer

, ( ).

, , . :

eventEmitter.subscribe('*:delt', handler);

, 2,3... N, , .

0

All Articles