One of the most useful programming concepts that my company has created over the past 16 months is also one of the simplest things that I’ve ever coded. It’s a client-side event pool that lives on the browser and that you interact with through JavaScript.
It’s purpose is simple: to allow arbitrary code to execute when an event is raised. You can think of it as a simple observer pattern implementation.
(You can download the source code here.)
To see just how simple it is, take a look the definition of the ClientEventPool … all 22 lines of it.
_ClientEventPool = function() { _ClientEventPool.initializeBase(this, null); }; _ClientEventPool.prototype = { initialize: function() { _ClientEventPool.callBaseMethod(this, 'initialize'); this._localEvents = this.get_events(); }, addEvent: function(eventName, handler) { this._localEvents.addHandler(eventName, handler); }, removeEvent: function(eventName, handler) { this._localEvents.removeHandler(eventName, handler); }, raiseEvent: function(eventName, sender, args) { var h = this._localEvents.getHandler(eventName); if (h) { h(sender, args); } } }; _ClientEventPool.registerClass("_ClientEventPool", Sys.Component); window.ClientEventPool = $create(_ClientEventPool, {"id":"ClientEventPool"}, null, null, null);
To use the event pool, I can simply register a handler for the event, and then raise the event like so.
ClientEventPool.addEvent("Test", function(sender, args) { alert("hello!"); }); ClientEventPool.raiseEvent("Test", this, Sys.EventArgs.Empty);
(In case you’re interested, the event pool relies upon ASP.NET AJAX Sys.Component’s .NET-style eventing mechanism, but in reality, using Sys.Component was just a convenience. Because Functions in JavaScript are nothing more than objects, executing functions that are assigned to properties, is really easy and is the concept of .NET delegates, are built into the language. This object could have easily been created without using anything from ASP.NET AJAX.)
(Shameless above-the-fold plug: If you’re a control developer who adds AJAX functionality to their server controls, you might be interested in my new book: Advanced ASP.NET AJAX Server Controls for .NET 3.5. Also, there’s a preview chapter in CoDe magazine.)
