In Rails 3, suppose I have the following code:
Controller
...
format.js # create.js.erb
...
create.js.erb
$('#element').html("new content");
View form
...
button_to 'Create', element, remote: true
I wonder how the JS in the create.js.erb file gets called.
My guess is that it returns JS code, and some Rails helpers invoke it when it’s received. Is this correct, or is there any other kind of magic going on here?
EDIT
Short answer: Basically, your assumption is correct, it will return the JS code which will then be executed.
Slightly longer answer: There is some magic behind it, though.
When the button is clicked, it will fire a JSON request to the create url, but asking for the format ‘js’ instead.
The controller then knows that the format expected is ‘js’ and, after running the
createaction, will render the template for that format —create.js.erb.Rails knows that it should do this custom JSON request because of the
:remote => trueoption. It adds adata-remote=trueattribute to the link element.Then, a handler specified in
rails.js(link) is attached to every element with this data-attribute, which takes care of the rest.Original Answer below
Rails uses a technique called Unobtrusive Javascript to attach the handlers you specify on .js files to their respective events.
You can read more about it on this (more specifically part 3) and this article.
Or, you could take the most fun route and take a look at the
rails.jsfile to see how all the magic works 🙂