Skip to content

Instantly share code, notes, and snippets.

@muloka
Forked from jamis/behaviors.js
Created January 4, 2011 20:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muloka/765398 to your computer and use it in GitHub Desktop.
Save muloka/765398 to your computer and use it in GitHub Desktop.
// An Unobtrusive Javascript (UJS) driver based on explicit behavior definitions. Just
// put a "data-behaviors" attribute on your view elements, and then assign callbacks
// for those named behaviors via Behaviors.add.
var Behaviors = {
add: function(trigger, behavior, handler) {
document.observe(trigger, function(event) {
var element = event.findElement("*[data-behaviors~=" + behavior + "]");
if (element) handler(element, event);
});
}
};
/*
EXAMPLE
-- step 1
erb:
<%= link_to "Add an alias", "#", "data-behaviors" => "add-alias" %>
html:
<a data-behaviors="add-alias" href="#">Add an alias</a>
N.B.: Elements can have multiple behaviors, too: just give a space-delimited
list of behavior names in the “data-behaviors” attribute.
-- step 2
Behaviors.add("click", "add-alias", function(element, event) {
// ...
});
sources:
http://weblog.jamisbuck.org/2010/3/2/unobtrusive-yet-explicit
http://prototypejs.org/api/event/observe
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment