Thursday, July 23, 2015

Event Bus implementation in Javascript

I have some difficult experience on working with javascript, even I'm a programmer, probably because my expertise lies in server side stuff.

Just recently, I found a nice topic about Event Bus, which is somehow similar to publisher/subscriber  pattern. This pattern helps the two classes can communicate indirectly with each other without "aware" about the existence of each other, in the way of publisher/ subscriber.
I see in java, there's a nice Event Bus library called guava, this library is easy to used thanks to good API and actively maintained. In C#, there's a library called TinyMessenger, which is also easy to use.

Looking at javascript, I'm struggling a little bit to find a good Event Bus library, and see there're some options (such as $.Callbacks in JQuery). However, the code seems to be hard for me to understand and use, possibly I'm "naive" on JScript.

So, I decided to implement it myself. Visit some nice articles on blog and forum, I manage to implement myself.

var EventBus = {
   // Storage of all event listeners, in this order: {eventName: {functionName:callback}}
    eventListeners: {},
  // Register event listener
    subscribe: function(evName,fName,_callback){
        if(!this.eventListeners[evName]){
            this.eventListeners[evName] = {};
        }
        this.eventListeners[evName][fName]=_callback;  
    },

   // Un-register event listener
    unSubscribe: function(evName,fName){
        if(!this.eventListeners[evName]){
            return;
        }
        if(!this.eventListeners[evName][fName]){
            return;
        }
        this.eventListeners[evName][fName] = null;
    },

  // Publish new data on particular event
    publish: function(evName, args){
        if(!this.eventListeners[evName]){   
            return;
        }
        var callBackList = this.eventListeners[evName];
        for (fN in callBackList) {
            var func = callBackList[fN];
            if(typeof func == "function"){
                func(args);               
            }
        }
    }
};


To use it, quite simple.

EventBus.subscribe("TestEvent","testFunc", function(msg) {alert(msg + " testFunc");});
EventBus.publish("TestEvent", ,"Test Msg");
EventBus.unSubscribe("TestEvent","testFunc");


This is a simple implementation of Event Bus, so it suffers some limitations (as far as I can see):
- The message transfers is not wrapped in object, you can enhance this by define the object type yourself to frame the data structure to send
- There's no order of the callback for particular event, so the called order of callback is random. You may add one more order into the subscribe method in EventBus object.

Disclaimer: the code here is free to use/ modify/ redistribute. However, the shared of better implementation is highly appreciated. BTW, I'm not responsible for any problem/ issue for this code snippet usage. So take your own risk on using it.

Happy coding.