Created
December 13, 2012 00:30
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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