Created
January 9, 2013 19:00
-
-
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.
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
/*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(); | |
} | |
} | |
}); | |
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
<h1>Example HTML</h1> | |
<div id="clickDiv" data-handler="clickHandle"></div> | |
<input name="find" id="quickFind" data-handler="findHandle" data-event="keyup"> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great example! Thank you.