當創建一個複雜的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);
你最終走哪條路?我目前正在努力做出同樣的決定。即使提出問題一年後,似乎也沒有明確的數據可以幫助做出選擇。全球的游泳池看起來更加自由,內存消耗更少,但是當系統開始變得非常龐大時,我想知道它是否會變得難以管理複雜。 – nicholas 2012-11-16 22:45:22