Rails 3 UJS driver events

非 Y 不嫁゛ 提交于 2019-12-03 10:06:49

The idea of UJS is to move the javascript code out of the views into separate js files. The way you're doing it is defeating that goal. Instead, I believe you should have a js file with a "dom:loaded" or similar handler that sets up handlers for rails callbacks and other events.

Something like (using prototype):

(function () {

  $(document).on('dom:loaded', function (event) {

    $$('a[data-remote=true]').each(function (link) {
      link.on('ajax:complete', function (request) {
        // do something
      });
    });

  });

}());

This way all javascripts are separated from the view, which is the idea of unobtrusive javascript.

After looking at rails source code, I came up with this solution:

  def javascript_event_tag(name, event, &block)
    content = "Event.observe('#{name}', '#{event}', function() {"
    content = content + update_page(&block)
    content = content + "});"

    content_tag(:script, javascript_cdata_section(content))
  end

This makes it easier to react to UJS events:

<div id="wait" style="display:none">
    <img src="/images/ajax-loader.gif"> Please wait...
</div>

<%= link_to 'ajax call', 'code_on_controller', :id => "mylink", :remote => true %>

<%= 
   javascript_event_tag('mylink', 'ajax:before') do |page|
     page.show 'wait'
   end
 %>
 <%= 
   javascript_event_tag('mylink', 'ajax:complete') do |page|
     page.hide 'wait'
   end
 %>

Instead of having to write raw prototype or jquery code, you can use rails helpers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!