Created
October 16, 2015 20:54
-
-
Save kara-ryli/50d0e68451ec2fb1ce7b to your computer and use it in GitHub Desktop.
Dead-simple event handling polyfills. Based largely on http://youmightnotneedjquery.com/
This file contains hidden or 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
/** | |
* Dead-simple event handling polyfills. Based largely on | |
* http://youmightnotneedjquery.com/ | |
*/ | |
/** | |
* IE-safe removeEventListener polyfill. Not exported to avoid bugs | |
* caused by wrapping the event handler in IE8. | |
* | |
* @param {Window|Document|HTMLElement} el Element to listen on | |
* @param {String} eventName The event to register | |
* @param {Function} handler Event handler | |
*/ | |
function off(el, eventName, handler) { | |
if (el.removeEventListener) { | |
el.removeEventListener(eventName, handler); | |
} else { | |
el.detachEvent("on" + eventName, handler); | |
} | |
} | |
/** | |
* IE8-safe addEventListener polyfill | |
* | |
* @param {Window|Document|HTMLElement} el Element to listen on | |
* @param {String} eventName The event to register | |
* @param {Function} handler Event handler | |
* @return {Function} Detaches the handler when called | |
*/ | |
function on(el, eventName, handler) { | |
var h; | |
if (el.addEventListener) { | |
h = handler; | |
el.addEventListener(eventName, handler); | |
} else { | |
h = function () { | |
handler.call(el, window.event); | |
}; | |
el.attachEvent("on" + eventName, h); | |
} | |
return function detach() { | |
if (el) { | |
off(el, eventName, h); | |
el = h = null; | |
} | |
}; | |
} | |
exports.on = on; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment