Simple JavaScript event model

by Mads Kristensen 20. November 2008 02:08

At work we are using a lot of JavaScript for all of our user controls and other ASP.NET components. I’m guessing that so are you. Our solution is to add a .js file per each user control and then load them on the page dynamically as explained here. That is a great way to componentize your web application.

Bad behavior

The problem is when an action on one user control’s JavaScript effects elements on other user controls. An example could be the page header where it says Signed in as Joe. When you are on the update profile page and change your name from Joe to Johnny using AJAX, then you don’t update the header element. If you do, you probably reference the DOM element from your profile update script directly. This is bad since the header and profile are located in two different user controls and thus haven’t got a clue about the existence of each other. Why should the JavaScript treat them differently?

Good behavior

What you really want to do is to use an event model. Then it works like so: 

The user changes his name to Johnny and the AJAX function in JavaScript triggers an event called profileNameUpdated and passes the new name along as a parameter. The page header have already told the event model to subscribe to the profileNameUpdated event and so it now catches the event triggered by the profile. It reads the new name and updates its own DOM element.

The code

Amazingly, the JavaScript code for this is less than 1KB and works on all websites, platforms and browsers. This is what it looks like.

// The constructor of the eventFramework
function eventFramework()
{
 this.handlers = [];
}

// Triggers the event specified by the name and passes the eventArgs to listeners
eventFramework.prototype.trigger = function(name, eventArgs)
{     
  for(var i = 0; i < this.handlers.length; i++)
  {
  if(this.handlers[i].eventName == name)
   this.handlers[i].eventHandler.call(this, eventArgs);
 }
}

// Adds a listener/subscriber to the event specified by the 'name' parameter
eventFramework.prototype.addListener = function(name, handler)
{
  if(typeof(name) != 'string' || typeof(handler) != 'function')
  {
  throw new SyntaxError("Invalid parameters when creating listener with the following arguments: 'Name': " + name + ", 'Handler': " + handler);
  }
 
  this.handlers.push({ "eventName" : name, "eventHandler" : handler });
}

// Initializes the eventFramework and makes it available globally
var events = new eventFramework();

Implementation

Download the .js file below and add it to your site. It should be the first JavaScript to be included in the <head> element of your pages.

When the script is included, it is now possible to start triggering and listening to events.  To trigger an event, simple write this:

events.trigger('profileNameUpdated', 'Johnny');

You can also pass objects or JSON as a parameter like so:

events.trigger('profileNameUpdated', {'name':'Johnny', 'oldName':'Joe'});

To subscribe or listen to these events, you simply add the following to any user control or JavaScript file:

events.addListener('profileNameUpdated', eventListener);

function eventListener(eventArgs)
{
  alert(eventArgs);
}

The eventArgs parameter will contain whatever was passed along by the trigger.

Download

eventmodel.js (966,00 bytes)

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Tags:

Client-side

Comments

11/20/2008 4:14:10 AM #

Chris Pietschmann

Rather interesting that you posted on this topic rather close to when I did (2 weeks ago in fact). It may be of interest for those interested in this post to also read/view mine.

pietschsoft.com/.../...ent-Driven-Programming.aspx

I have also written another post in the "Event Driven" theme on how to implement it using the ASP.NET AJAX library:

pietschsoft.com/.../...-Component-with-Events.aspx

Chris Pietschmann United States |

11/20/2008 4:38:07 AM #

Mads Kristensen

Interesting posts, Chris. I didn't know you could do all that in ASP.NET AJAX. Very powerful.

The event stuff that's possible in JavaScript seems relatively unknown to most people. We've used it at work for a long time to everybody's delight.

Mads Kristensen Denmark |

11/20/2008 9:53:43 PM #

pingback

Pingback from alvinashcraft.com

Dew Drop - November 20, 2008 | Alvin Ashcraft's Morning Dew

alvinashcraft.com |

11/30/2008 8:32:30 AM #

trackback

Simple JavaScript event model

You are voted (great) - Trackback from Web Development Community

Web Development Community |

12/1/2008 11:17:20 PM #

pingback

Pingback from javapronews.com

Java Programming News  » Blog Archive   » Componentizing Your Web Applications with Java - JavaProNews.com

javapronews.com |

1/11/2009 6:04:16 AM #

hiking backpacks

I had tried reference the DOM element from your profile update script directly but didn't know how. So this mean I don't update the header element.

hiking backpacks United States |

5/17/2009 9:02:14 PM #

trackback

Simple JavaScript event model

Simple JavaScript event model

.Net |

Comments are closed

About the slave

Mads Kristensen Mads Kristensen
Web developer at ZYB and founder of BlogEngine.NET. More...

LinkedIn ZYB Facebook Last.fm Twitter View Mads Kristensen's profile on Technorati

The Lounge

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008