-
Notifications
You must be signed in to change notification settings - Fork 55
Mediator
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 scope and certain messages to be heard by everyone ( frontend and backend). So , we decided to introduce message scope
.
pubSub = {
publish: function({
msg:"message goes here",
data:data, // optional - data passed to the listener functions as a second parameter
msgScope:[], // array of message scopes
callback:function // optional - called immediately after publishing.
}){
//implementation goes here
} ,
subscribe:function({
msg:"message goes here",
listener:function, // registered against the message, accepts msg and data as parameters
msgScope:[], // array of message scopes
context:this // optional - Context with which the listener is called
callback:function // optional - called after the subscription is over
}){
//implementation goes here
}
}
msgScope
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.
For example, on the sidebar controller the user chooses to generate data through simulation. Now we want the frontend to show a notification asking the user to wait, so the message is passed to the frontend logic. Meanwhile the same message has to be heard by the
core
to start required 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
msgScope
.
var sub1 = pubSub.subscribe({
msg:"request for generate simulated data",
listener:generate,
context:Generator,
msgScope:["core"]
}),
sub2 = pubSub.subscribe({
msg:"request for generate simulated data",
listener:updateView,
context:Controller,
msgScope:["module"]
});
//somewhere else in the code
$("#button").on("click",function(){
// the last but one parameter has value ["core","module"]
// scopes are present in array. So message is heard by subscribers of scope "core" and
// "module" i.e. sub1 and sub2 respectively.
pubSub.publish({
msg:"request for generate simulated data",
data:"binomialCoinToss",
msgScope:["core","module"],
callback:cb
});
});