JavaScript Event Hub

by rsutton 7. October 2009 09:30

I’m am currently creating a UI to do a bulk add operation and one of the main features that this form must have is speed.  It must be quick to do maneuver around the form and get at various data.  So in order to do this I have decided to go the no postbacks, ajax and JavaScript route.  The problem is trying to deal with all the interactions and maintaining the state of the form, because I will be constantly entering data and making ajax request.  In my effort simplify things I created what I call an EventHub.  The idea is really simple.  Here is the code.

    1 

    2 cw.EventHub = function() {

    3     var messages = [];

    4 

    5     return {

    6         subscribe: function(message,key,subscriber) {

    7             // setup the message subscriber list of this is a new message

    8             if (!messages[message])

    9                 messages[message] = [];

   10 

   11             // add the subscriber

   12             messages[message][key] = subscriber;

   13         },

   14         unsubscribe: function(message,key) {

   15             delete messages[message][key];

   16         },

   17         dispatch: function(message,data) {

   18             for (var key in messages[message])

   19                 messages[message][key](data);

   20         }

   21     };

   22 } ();

You subscribe to events like this.

 

EventHub.subscribe("OrderDateUpdated", "myKey", function(data) { alert('Order ' + data.id + ' Updated'); });

 

I added the key during the subscribe so that you can unsubscribe messages if needed like this.

 

EventHub.unsubscribe("OrderDateUpdated", "myKey");

 

Then you send messages like this.

 

EventHub.send("OrderDateUpdated", { id: '1234' });

 

Like I said there is nothing too complex here and it has made my life a lot easier in dealing with UI interactions.  Adding additional behavior to a form is simply a function of subscribing to the published event and then doing some work.

Tags:

Development

Comments are closed

Powered by BlogEngine.NET 1.4.5.0
Theme by Extensive SEO

Profile

Member of the Church of Jesus Christ of Latter-Day Saints, Developer and IT Professional