Created
July 14, 2015 12:02
-
-
Save oslego/b2b1907f5d1c5a052c3f to your computer and use it in GitHub Desktop.
DOM events wrapper with auto-unbind from @toddmotto
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
// 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