Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* event handler utility
* @param {element} element DOM element to attach event listener
* @param {object} context The context the handler will be run in - can be overriden
* @return {function} Specify event
*/
function event(element, context){
// Assume modern browser
var pasteeater = false
// Check to see whether we're dealing with an old browser
// and change pasteeater to true if old browser detected
if(!element.addEventListener && element.attachEvent){
pasteeater = true
}
/**
* specify event
* @param {string} event The event name
* @return {function} Add handler
*/
return function(event){
/**
* attach handler
* @param {function} handler event handler
* @param {object} data Any extra data to pass to the handler
* @param {object} _context Override the context the handler is run in
* @return {function} Function to remove event listener
*/
return function(handler, data, _context){
context = _context || context
if(!handler.call){
throw Error('Callback is not a function')
}
// create new handler function based on arguments passed
var _handler = function(){
handler.call(context || element, event, data)
}
// fallback for old browsers
if(pasteeater){
element.attachEvent("on"+event, _handler)
} else {
element.addEventListener(event, _handler, false)
}
/**
* remove handler
* @return {function} Call this function to remove event listener
*/
return function(){
// fallback for old browsers
if(pasteeater){
element.detachEvent("on"+event, _handler)
} else {
element.removeEventListener(event, _handler, false)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.