5

当创建一个复杂的JS应用程序时,使用全局观察者对象触发事件并且所有其他对象订阅的优点和缺点与混合或原型设计所有负责触发自己事件的对象的pub/sub方法?全球观察对象与mixin的优缺点

举例来说,一种纸牌游戏,有经销商,球员,和表对象(伪码十岁上下如下):

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

你最终走哪条路?我目前正在努力做出同样的决定。即使提出问题一年后,似乎也没有明确的数据可以帮助做出选择。全球的游泳池看起来更加自由,内存消耗更少,但是当系统开始变得非常庞大时,我想知道它是否会变得难以管理复杂。 – nicholas 2012-11-16 22:45:22

回答

0

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

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

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

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

+0

我希望得到一个更全面的答案,列出一系列利弊和一些可能的性能数据来支持它,但由于没有其他人回答,因为您提供了一些有用的反馈,所以您会得到支票。谢谢! – salmonete 2011-12-27 23:06:48