Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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() {
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) {
// 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 () {
}, 2000);
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.