Search code examples
javascriptdesign-patternsbackbone.jsobserver-patternpublish-subscribe

Pros/cons of a global observer object vs. a mixin


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

Take for example a card game which has dealer, player, and table objects (psuedocode-ish follows):

// "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);

vs

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

Solution

  • In your examples both seem a valid choice, but the difference can be seen when dealing with dynamic event names (also dynamic 'publisher' names).

    So using a global emitter is good when you need to subscribe to events using a wildcard. Example:

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

    Another difference is that you can have one variable instead of 2,3 ... N, which is better for memory I believe.