Skip to content
selvam1991 edited this page Apr 25, 2013 · 5 revisions

There are many publish/subscribe messaging systems implemented in javaScript over time. Every implementation has its own perks. For people with priority to performance, have a look at this comparison.

All the implementations have more or less the same underlying concept. They have a Publisher and Subscriber with one-to-one correspondence. The object wrapping the publisher and subscriber holds a private list of messages. When a function subscribers to a message, an entry is made in the list if its not there already.

After studying the all the implementations and accounting for our project requirements, we decided to modify vanilla js implementation with some features of pubSubJs.

In our project, we need certain messages to be heard within the frontend and certain messages to be heard by everyone ( frontend and backend). So , we decided to introduce message scope.

pubSub = {
   publish: function(message,data,messageScope,callback){
      //implementation goes here
   } ,
   subscribe: function(message,function,scope,messageScope){
      //implementation goes here
  }
 }

messageScope can take values such as "core" , "module" , "app" etc.

  • "core" will broadcast the message to all backend subscribers.
  • "module" broadcasts to all the subscribers with that angular module.
  • "app" broadcasts to all the frontend angular modules.

Lets consider an example

For example, on the sidebar controller the user chooses to generate data through simulation. Now we want the frontend to show a message asking the user to wait. Meanwhile the same message has to be heard by the core to start processing.

Now we can achieve this my sending 2 messages. But as the complexity of the application increases, this is not a scalable solution. Hence the messageScope.

var sub1 = pubSub.subscribe("request for generate simulated data",generate(),Generator,"core"),
sub2 = pubSub.subscribe("request for generate simulated data",updateView(),Controller,"module");

//somewhere else in the code
$("#button").on("click",function(){
   // the last but one parameter has value "core/module"
   // scopes are delimited using '/' . So message is heard by subscribers of scope "core" and 
   // "module" i.e. sub1 and sub2 respectively.
   pubSub.publish("request for generate simulated data","binomialCoinToss","core/module",cb);
});
Clone this wiki locally