Last active
August 29, 2015 13:56
-
-
Save dhigginbotham/8832333 to your computer and use it in GitHub Desktop.
event handling on data-attrs
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
(function (root) { | |
/** | |
* data events add event listeners | |
* on data-attributes, ie8+ | |
* | |
* author: dhigginbotham | |
* license: MIT | |
*/ | |
var priv = {}, | |
events = {}; | |
/** | |
* internal events on the dom | |
*/ | |
priv.events = []; | |
/** | |
* helper to get index of event | |
*/ | |
priv.contains = function (attr) { | |
return priv.events.indexOf(attr); | |
}; | |
/** | |
* get elements querySelector | |
*/ | |
priv.select = function (attr) { | |
return document.querySelector('[data-' + attr + ']'); | |
} | |
/** | |
* turns an event on | |
*/ | |
events.on = function (attr, ev, fn) { | |
var el = priv.select(attr); | |
if (priv.contains(attr) == -1) priv.events.push(attr); | |
if (el.addEventListener) { | |
return el.addEventListener(ev, fn, false); | |
} else if (el.attachEvent) { | |
return el.attachEvent('on' + ev, fn); | |
}; | |
}; | |
/** | |
* turns an event off | |
*/ | |
events.off = function (attr, ev, fn) { | |
var el = priv.select(attr); | |
if (priv.contains(attr) != -1) priv.events.splice(priv.contains(attr), 1); | |
if (el.removeEventListener) { | |
return el.removeEventListener(ev, fn, false); | |
} else if (el.detachEvent) { | |
return el.detachEvent('on' + ev, fn); | |
}; | |
}; | |
/** | |
* toggle an event on or off, so you don't have | |
* to keep track of it. | |
*/ | |
events.toggle = function (attr, ev, fn) { | |
if (priv.contains(attr) == -1) { | |
events.on(attr, ev, fn); | |
} else { | |
events.off(attr, ev, fn); | |
} | |
}; | |
/** | |
* expose public api | |
*/ | |
if (typeof SM != 'undefined') { | |
SM.namespace('SM.dataEvents'); | |
_.extend(SM.dataEvents, events); // feels pointless | |
} else { | |
root.dataEvents = events; | |
} | |
}(window)); |
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
var handler = function (e) { | |
console.log(e); | |
}; | |
dataEvents.toggle('someDataAttr', 'click', handler); // first time, turns it on, second time turns it off. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment