Created
September 17, 2013 12:41
-
-
Save husa/6593823 to your computer and use it in GitHub Desktop.
reusable custom events
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
var Events = function() { | |
var events = {}; | |
return { | |
on : function(event, callback) { | |
events[event] = events[event] || []; | |
events[event].push(callback); | |
return this; | |
}, | |
off : function(event, callback) { | |
var callbacks; | |
// if no arguments - remove all handlers | |
if (!event) { | |
events = {}; | |
return this; | |
} | |
callbacks = events[event]; | |
// nothing to remove | |
if (!callbacks) { | |
return this; | |
} | |
// if no callback remove all handlers | |
if (!callback) { | |
events[event] = []; | |
return this; | |
} | |
//find and remove handler | |
for (i = 0; i < callbacks.length; i++) { | |
if (callbacks[i] === callback) { | |
events[event].splice(i, 1); | |
return this; | |
} | |
} | |
}, | |
fire : function(event) { | |
var i, n, args, | |
callbacks = events[event]; | |
if (callbacks) { | |
args = Array.prototype.slice.call(arguments, 1); | |
for (i = 0, n = callbacks.length; i < n; i++) { | |
callbacks[i].apply(null, args); | |
} | |
} | |
return this; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment