当创建一个复杂的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