Search code examples
ruby-on-rails-3ujs

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


Solution

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