Skip to content

Instantly share code, notes, and snippets.

@jarek-foksa
Created July 19, 2011 09:14
Show Gist options
  • Save jarek-foksa/1091798 to your computer and use it in GitHub Desktop.
Save jarek-foksa/1091798 to your computer and use it in GitHub Desktop.
/**
* Custom events
*
* (c) 2010 Jeremy Ashkenas, DocumentCloud Inc.
* License: MIT License
*
* Usage:
* > bind('widgetClicked', function() {
* console.log("Button was clicked");
* }
* > trigger('widgetClicked');
*
*/
// Bind an event, specified by a string name, `ev`, to a `callback` function.
// Passing `"all"` will bind the callback to all events fired.
window.bind = function(ev, callback) {
var calls = window._callbacks || (window._callbacks = {});
var list = window._callbacks[ev] || (window._callbacks[ev] = []);
list.push(callback);
return this;
}
// Remove one or many callbacks. If `callback` is null, removes all
// callbacks for the event. If `ev` is null, removes all bound callbacks
// for all events.
window.unbind = function(ev, callback) {
var calls;
if (!ev) {
window._callbacks = {};
} else if (calls = window._callbacks) {
if (!callback) {
calls[ev] = [];
} else {
var list = calls[ev];
if (!list) return this;
for (var i = 0, l = list.length; i < l; i++) {
if (callback === list[i]) {
list.splice(i, 1);
break;
}
}
}
}
return this;
}
// Trigger an event, firing all bound callbacks. Callbacks are passed the
// same arguments as `trigger` is, apart from the event name.
// Listening for `"all"` passes the true event name as the first argument.
window.trigger = function(ev) {
var list, calls, i, l;
if (!(calls = window._callbacks)) return this;
if (list = calls[ev]) {
for (i = 0, l = list.length; i < l; i++) {
list[i].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
if (list = calls['all']) {
for (i = 0, l = list.length; i < l; i++) {
list[i].apply(this, arguments);
}
}
return this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment