Where are Rails 3 custom JavaScript events defined?
Asked Answered
K

1

19

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

Keeter answered 31/12, 2010 at 21:40 Comment(2)
Bryan, please stop signing your messages - it's a violation of stackoverflow policies. thanks!Illampu
Whoops, sorry! Will do (or not do any more :). Thanks for telling me.Keeter
P
20

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.

Pauwles answered 31/12, 2010 at 21:54 Comment(3)
Perfect... pointing out that they are namespaced events helps clear things up significantly. Thanks Chris!Keeter
Ok, but wait... so where are '*.rails' events triggered? I don't see them in jquery-ujs...Keeter
They are triggered by the regular events as well as any .rails events. It's only when you want to do something special with just the .rails handlers (like unbinding just the rails handlers or triggering them without triggering the regular handlers) that the namespacing comes into play. See docs.jquery.com/Namespaced_EventsLeandroleaning

© 2022 - 2024 — McMap. All rights reserved.