Skip to content

Instantly share code, notes, and snippets.

@tkh44
Created January 9, 2013 19:00
Show Gist options
  • Save tkh44/4495846 to your computer and use it in GitHub Desktop.
Save tkh44/4495846 to your computer and use it in GitHub Desktop.
Automatically bind events from data-attribute. This is based off of sparky.js, but ported to YUI3.
/*Automatic binding handler
*Attribute data-handler is the function in Events.handlers that handles the event
*Attribute data-event is the event to bind to element. Defaults to click if none is provided
* -To attach multiple events seperate them with '|'. Ex. data-event="click|focus"
*Attribute data-binded can be set to false to prevent the event from being attached to the element at run time.
* -Set attribute to true then run Events.bindEvents() to bind the event. Elements that have already been bound are skipped.
*/
Events = {
handlers: {
},
bindEvents: {
Y.all('[data-handler]').each(function(node){
var eventEl = node,
handler = eventEl.getAttribute('data-handler'),
eventType = eventEl.getAttribute('data-event').split('|') || ['click'],
binded = eventEl.getAttribute('data-binded');
if(typeof Events.handlers[handler] !== 'undefined') {
if (binded !== 'false') {
eventEl.setAttribute('data-binded', 'true');
eventEl.on(eventType, Events.handlers[handler]);
}
}
},
init: function(){
Events.bindEvents();
}
}
});
<h1>Example HTML</h1>
<div id="clickDiv" data-handler="clickHandle"></div>
<input name="find" id="quickFind" data-handler="findHandle" data-event="keyup">
@joeygrable94
Copy link

Great example! Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment