在创建复杂的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);
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 :(得分:0)
在您的示例中,两者似乎都是有效的选择,但在处理动态事件名称(也是动态“发布者”名称)时可以看到差异。
因此,当您需要使用通配符订阅事件时,使用全局发射器是很好的。例如:
eventEmitter.subscribe('*:delt', handler);
另一个不同之处在于,您可以使用一个变量而不是2,3 ... N,这对于我相信的内存会更好。