Created
October 15, 2013 12:30
-
-
Save compact/6990866 to your computer and use it in GitHub Desktop.
Basic custom event handling without having to use the DOM Event Model. Uses Underscore.js or Lo-Dash.
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 (events, _) { | |
'use strict'; | |
// keys are event names | |
var handlers = {}; | |
/** | |
* Bind the given handler to the given event. | |
* @param {String} event | |
* @param {Function} handler | |
*/ | |
events.on = function (event, handler) { | |
if (typeof handlers[event] !== 'object') { | |
handlers[event] = []; | |
} | |
handlers[event].push(handler); | |
}; | |
/** | |
* Unbind the given handler from the given event. | |
* @param {String} event | |
* @param {Function} handler | |
*/ | |
events.off = function (event, handler) { | |
var index = _.indexOf(handlers[event], handler); | |
if (index === -1) { | |
console.warn('The following handler was not found for event ' + event + | |
':', handler); | |
} else { | |
handlers[event].splice(index, 1); | |
} | |
}; | |
/** | |
* Trigger the given event by calling all its handlers. | |
* @param {String} event | |
*/ | |
events.trigger = function (event) { | |
var args = Array.prototype.slice.call(arguments, 1); | |
_.each(handlers[event], function (handler) { | |
handler.apply(events, args); | |
}); | |
}; | |
return events; | |
}(events || {}, _)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment