Skip to content

Instantly share code, notes, and snippets.

@elithompson
Created May 25, 2011 00:11
Show Gist options
  • Save elithompson/990042 to your computer and use it in GitHub Desktop.
Save elithompson/990042 to your computer and use it in GitHub Desktop.
A simple C#-style event system in Javascript
function createEvent() {
var handlers = [];
var event = function(handler) {
if (arguments.length === 0) {
for(var i = 0, action; (action = handlers[i]); i++) {
action();
}
return;
}
handlers.push(handler);
};
return event;
}
// example usage
var person = {
age: 99,
onDeath: createEvent(),
birthday: function() {
if (++this.age >= 100) {
this.onDeath();
}
}
};
person.onDeath(function() { console.log('I died'); });
person.birthday(); // console prints 'I died'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment