Synchronous vs. asynchronous for publish subscribe communication between JavaScript objects
Posted
by
natlee75
on Programmers
See other posts from Programmers
or by natlee75
Published on 2012-04-13T16:26:04Z
Indexed on
2012/04/13
17:42 UTC
Read the original article
Hit count: 311
JavaScript
I implemented the publish subscribe pattern in a JavaScript module to be used by entirely client-side oriented JavaScript objects. This module has nothing to do with client-server communications in any way, shape or form.
My question is whether it's better for the publish method in such a module to be synchronous or asynchronous, and why.
As a very simplified example let's say I'm building a custom UI for an HTML5 video player widget:
One of my modules is the "video" module that contains the VIDEO element and handles the various features and events associated with that element. This would probably have a namespace something like "widgets.player.video."
Another is the "controls" module that has the various buttons - play, pause, volume, scrub, fullscreen, etc. This might have a namespace along the lines of "widgets.player.controls."
These two modules are children of a parent "player" module ("widgets.player" ??), and as such would have no inherent knowledge of each other when instantiated as children of the "player" object.
The "controls" elements would obviously need to be able to effect some changes on the video (click "Play" and the video should play), and vice versa (video's "timeUpdate" event fires and the visual display of the current time in the controls should update).
I could tightly couple these modules and pass references to each other, but I'd rather take a more loosely coupled approach by setting up a pubsub type module that both can subscribe to and publish from.
SO (thanks for bearing with me) in this kind of a scenario is there an advantage one way or another for synchronous publication versus asynchronous publication? I've seen some solutions posted online that allow for either/or with a boolean flag whereas others automatically do it asynchronously. I haven't personally seen an implementation that just automatically goes with synchronous publication... is this because there's no advantage to it?
I know that I can accomplish this with features provided by jQuery, but it seems that there may be too much overhead involved here. The publish subscribe pattern can be implemented with relatively lightweight code designed specifically for this particular purpose so I'd rather go with that then a more general purpose eventing system like jQuery's (which I'll use for more general eventing needs :-).
© Programmers or respective owner