As I look through the Rails 3 jquery-ujs code, I notice that it binds to custom JavaScript events (submit.rails, click.rails, etc). Does anyone know where are these custom '.rails' events defined? I'm just trying to better understand how the UJS stuff in Rails 3 works so I can use it more effectively...
.js.erb files are for controller actions, such as create, when you want javascript to be executed when the action completes. For example, when you want to submit a form via ajax and want display an alert when everything is done, you would put the $('#business_submit').
Rails UJS (Unobtrusive JavaScript) is the JavaScript library that helps Rails do its magic when we use options like remote: true for many of the html helpers. In this article I'll try to explain the main concept of how this works to make it transparent for the user.
These are namespaced events. There's no definition for them; click.rails
is the same as click
, but because it's namespaced with rails
, you can unbind or trigger the Rails-specific event handlers without invoking all of the click
events on an element.
For example, assume that you have some element, <div class='foo' data-remote='true'>
, and rails.js binds
$("*[data-remote='true']").bind("click.rails", function() { ... })
In your code, you also have:
$(".foo").click(function() { ... });
Now, Rails may want to invoke that remote handler at some point, but if it just called $(this).click()
, then it would invoke all click handlers on the item, including your custom one, which might produce undesired behavior. Instead, it can call $(this).trigger('click.rails')
, and only the click handler it defined would be run.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With