Skip to content

Instantly share code, notes, and snippets.

@cjwainwright
Created December 13, 2012 00:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjwainwright/4273007 to your computer and use it in GitHub Desktop.
Save cjwainwright/4273007 to your computer and use it in GitHub Desktop.
A simple event maker. Creates a function to which other functions can be added and removed for execution when the outer function is called.
function event() {
var a = [].slice.call(arguments);
var fn = function() {
var scope = this;
var args = [].slice.call(arguments);
a.forEach(function(f){f.apply(scope, args);});
};
fn.add = function() {
a.push.apply(a, arguments);
return fn;
};
fn.remove = function(f) {
for(var i = a.length - 1; i >= 0; i--) {
if(a[i] === f) {
a.splice(i, 1);
}
}
return fn;
};
fn.clear = function() {
a.length = 0;
};
return fn;
}
// example usage
var el = document.body;
el.onclick = event();
el.onclick.add(function(){this.style.backgroundColor = 'red'});
el.onclick.add(function(){ var that = this; setTimeout( function() {that.style.backgroundColor = 'white'}, 1000); });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment