Answer the question
In order to leave comments, you need to log in
Why do Publisher-Subscriber event systems use strings to identify events?
In almost all implementations of the event system according to the "Publisher-Subscriber" pattern in Javascript (and not only), the event is identified through a unique string:
// публикация события
dispatcher.publish('user.profile.updated', {data: profileData});
// подписка на событие
dispatcher.subscribe('user.profile.updated', function(data) { console.log(data) });
class UserProfileUpdateEvent extends Event {...}
// публикация
dispatcher.publish(new UserProfileUpdateEvent(profileData));
// подписка
dispatcher.subscribe(UserProfileUpdateEvent, function(event) { console.log(event.data); });
instanceof
. In addition, the only possible way of publishing is introduced - if the event needs data and they are not transmitted, an exception will be thrown. Answer the question
In order to leave comments, you need to log in
Because the association of subscribers with the event is done by placing an array of handler functions in a hash under the key, which is the name of the event (or channel, if we are talking about pubsub). This is the simplest and most obvious mechanism. With the advent of Map from ES2015, any object can serve as a key, not just a string.
One of the ways to get rid of the so-called. "stringly typed" code - use type constructs
chrome.browserAction.onClicked.addListener(function callback)
, as done in Chrome extensions. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question