-
-
Save muloka/765398 to your computer and use it in GitHub Desktop.
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
// 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