Q
Q
qtuz2015-07-11 10:31:48
JavaScript
qtuz, 2015-07-11 10:31:48

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) });

With this approach, the event consists of two parts: a unique name and data that is passed with the event to the code that processes it.
Question: why are two independent data types used to identify an event, which is essentially a message that something has happened in the system? After all, an event can be an instance of a class that optionally provides data. Example:
class UserProfileUpdateEvent extends Event {...}

// публикация
dispatcher.publish(new UserProfileUpdateEvent(profileData));

// подписка
dispatcher.subscribe(UserProfileUpdateEvent, function(event) { console.log(event.data); });

With this approach, the event has a signature and a clear connection with the transmitted data. Such events can be inherited from each other and filtered by 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.
The question is rather theoretical, but so far I see only pluses in this approach. The need to keep track of the unique string of the event name seems terribly inconvenient to me.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Kitmanov, 2015-07-11
@qtuz

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.
I believe your approach has the right to life (and I like it even more than Google Chrome). But I'm afraid it won't be widely used.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question