My view on mechanism:
- Pattern wise publisher should just publish an event and should not care about listeners / subscribers for that topic / event.
- In case of JavaScript, lot of frameworks for Pub / Sub publishes event in Sync manner
- for example : framework just maintains map of event to function.
- on particular event occurrence, it iterates over subscribers and calls function one by one - > function_1.apply(context, args) and then function_2.apply(context, args)
- This makes it Synchronous as, unless and until function_1 finishes, function_2 is unaware that particular event happened.
What is an ideal way of implementing Pub / Sub in JavaScript ?
I add an "enqueue" parameter to my publish method that when truthy, wraps the actual publish in a setTimeout(..., 0) so that the publisher can choose to have the handling fire immediately, or have it enqueued in the JavaScript execution queue, allowing the current path of execution to complete first.
If you are maintaining your own list of subscribers, you can have the subscribe method implement the enqueue flag as an attribute of the subscription. Thus the publisher could enqueue individual subscribers based on their preference as indicated in their subscription.