Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where are Rails 3 custom JavaScript events defined?

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...

like image 444
Bryan Avatar asked Dec 31 '10 21:12

Bryan


People also ask

What is a JS Erb file?

.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').

What is Rails Ujs?

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.


1 Answers

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.

like image 151
Chris Heald Avatar answered Oct 13 '22 17:10

Chris Heald