Oct 1, 2011

Events in Javascript

One of the features of C# that I really enjoy is events. For the many folks out there who have never used C#, an event is an implementation of the observer pattern that allows objects to watch for certain notifications within other objects. For example in the Windows.Forms library the Button object has a Click event that you can bind an action to:

var button = new Button();
button.Click += (sender, ev) => {
MessageBox.Show("Hello, world!");
};

You can define events within your own classes and fire them easily:

public delegate void MyEventHandler();
public event MyEventHandler MyEvent;

// ... lots of code ...

// ... in some method that triggers the event:
if (MyEvent != null){
MyEvent();
}

Turns out this is fairly easily implemented in Javascript. This code here should do the trick:

function createEvent(eventName, obj){
var event = function() {
var ob;
for (var i = 0; i < obj[eventName].observers.length; i++){
ob = obj[eventName].observers[i];
ob.apply(ob, arguments);
}
};

event.observers = [];

event.add = function(observer) {
event.observers.push(observer);
};

event.remove = function(observer) {
var i = event.observers.indexOf(observer);
if (i >= 0){
event.observers.splice(i, 1);
}
};

obj[eventName] = event;
}

Now you can go like this:

var obj = {};

createEvent("test", obj);

obj.test.add(function(){
alert("Hello, world!");
});

obj.test();


You can try it by clicking here.

No comments: