在创建复杂的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);
Run Code Online (Sandbox Code Playgroud)
VS
// Pub/sub mixin/prototype version
dealer.deal …Run Code Online (Sandbox Code Playgroud) javascript design-patterns publish-subscribe backbone.js observer-pattern