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