Skip to content

Instantly share code, notes, and snippets.

@oslego
Created July 14, 2015 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oslego/b2b1907f5d1c5a052c3f to your computer and use it in GitHub Desktop.
Save oslego/b2b1907f5d1c5a052c3f to your computer and use it in GitHub Desktop.
DOM events wrapper with auto-unbind from @toddmotto
// addEventListener wrapper
// returns function for auto-unbinding
function on(elem, type, fn) {
elem.addEventListener(type, fn, false);
return function () {
off(elem, type, fn);
};
}
// removeEventListener wrapper
function off(elem, type, fn) {
elem.removeEventListener(type, fn, false);
}
// create an events binding function
// that stores all events inside an Array
function bindMyEvents() {
function someFn() {
console.log('hi');
}
var unbind = [
// each item inside the Array (once called) is
// the return value of the "on" function, where we
// can call it to unbind
on(document, 'click', someFn)
];
// return another closure that when called
// loops through our Array calling all returned closures
return function destroy() {
unbind.forEach(function (fn) {
fn();
});
};
}
// bind your events for whatever purposes
// and get the returned closure from "bindMyEvents"
// calling it will destroy all events
var destroy = bindMyEvents();
// when you're ready, destroy all events
setTimeout(function () {
destroy();
}, 2000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment