Lightweight JavaScript Events
I've found it handy on a few projects to mix in minimalistic event support to certain JavaScript objects. The basic idea is that you listen (aka "subscribe") for some event on an object, and get notified by the object when it fires (aka "publishes") that event, along with any parameters it decides to attach. This is ridiculously easy to implement in JavaScript, yet it's a really powerful abstraction mechanism for UI programming. It's even easier when you use a library like Prototype to take advantage of its Enumerable and Function extensions. Here it is in under 20 lines of code:
EventManager = {
notify: function() {
if (this._listeners) {
var args = $A(arguments), event = args.shift();
this._listeners.each(function(listener) {
listener[event] && function() {
listener[event].apply(this, args);
}.defer();
}, this);
}
},
listen: function(listener) {
this._listeners = this._listeners || [];
this._listeners.push(listener);
}
};To add event support to a class, just mixin the EventManager extension:
Foo = Class.create({
setX: function(x) {
this.x = x;
this.notify("setX", this.x);
}
});
Foo.addMethods(EventManager);And then get down to it:
var object = new Foo();
object.listen({
setX: function(x) {
alert("x was initialized to " + x);
}
});
object.setX(1);
That's about it. Let me know if it comes in handy.
Labels: javascript

