[英]Pros/cons of a global observer object vs. a mixin
When creating a complex JS application, what are the pros and cons of using a global observer object which fires events and which all other objects subscribe to vs. mixing in or prototyping pub/sub methods on all objects which are responsible for triggering their own events? 在创建复杂的JS应用程序时,使用全局观察对象的优缺点是什么,该对象触发事件以及所有其他对象订阅与混合或原型化pub / sub方法的所有对象,这些对象负责触发自己的事件?
Take for example a card game which has dealer, player, and table objects (psuedocode-ish follows): 以卡片游戏为例,其中包含经销商,玩家和桌面对象(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 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);
In your examples both seem a valid choice, but the difference can be seen when dealing with dynamic event names (also dynamic 'publisher' names). 在您的示例中,两者似乎都是有效的选择,但在处理动态事件名称(也是动态“发布者”名称)时可以看到差异。
So using a global emitter is good when you need to subscribe to events using a wildcard. 因此,当您需要使用通配符订阅事件时,使用全局发射器是很好的。 Example:
例:
eventEmitter.subscribe('*:delt', handler);
Another difference is that you can have one variable instead of 2,3 ... N, which is better for memory I believe. 另一个区别是你可以有一个变量而不是2,3 ... N,这对于我相信的内存更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.