全球观察者对象与混合的利弊

sal*_*ete 5 javascript design-patterns publish-subscribe backbone.js observer-pattern

在创建复杂的JS应用程序时,使用全局观察对象的优缺点是什么,该对象触发事件以及所有其他对象订阅与混合或原型化pub/sub方法的所有对象,这些对象负责触发自己的事件?

以卡片游戏为例,其中包含经销商,玩家和桌面对象(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);
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

ale*_*lex 0

在您的示例中,两者似乎都是有效的选择,但是在处理动态事件名称(也是动态“发布者”名称)时可以看到差异。

因此,当您需要使用通配符订阅事件时,使用全局发射器是很好的选择。例子:

eventEmitter.subscribe('*:delt', handler);
Run Code Online (Sandbox Code Playgroud)

另一个区别是你可以有一个变量而不是 2,3 ... N,我相信这对记忆更好。