轨道3 UJS驱动事件轨道、事件、UJS

2023-09-10 16:18:01 作者:温致如猫

据西蒙娜Carletti酒店博客文章,Rails的3 AJAX助手已经改变了很多。我们应该写更多的JavaScript与Rails 3的比我们用来与轨道2。

According to Simone Carletti blog post, Rails 3 ajax helpers have changed a lot. We are supposed to write more javascript with rails 3 than we used to with rails 2.

我试图找出如何出现一个Ajax加载GIF助益,而在一个Ajax查询磨合在轨道3路。我想出了这样的code,它使用了Rails 3的UJS驱动程序发送JavaScript事件。本例使用原型:

I tried to figure out how to show up an ajax loading gif -while an ajax query is running- in the "rails 3 way". I came up with this kind of code, which uses javascript events sent by the Rails 3 UJS driver. This example uses prototype:

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

<div>
    <%= link_to 'Get', 'finished', :id => "mylink", :remote => true %>
</div>

<%= javascript_tag do %>
        Event.observe('mylink', 'ajax:before', function(event) {
            $('wait').show();
        });
        Event.observe('mylink', 'ajax:complete', function(event) {
            $('wait').hide();
        });
<% end %>

这工作得很好,但我想这是可能的原型和Scriptaculous助手的帮助下写下这些AJAX事件的触发器,当我们用link_to_function例如就像:

This works well, but I wish it was possible to write these ajax events "triggers" with the help of the prototype and scriptaculous helpers, just like when we use link_to_function for example:

<%= 
  link_to_function("toggle visibility") do |page|
    page.toggle "wait"
  end
%>

有没有办法做到这一点,还是我们应该在JavaScript中直接写AJAX事件触发器,无论是原型或jQuery的?

Is there a way to do that, or are we supposed to write ajax events "triggers" in javascript directly, either prototype or jquery?

最好的问候,

菲利普·郎

推荐答案

在看着铁轨源$ C ​​$ C,我想出了这个解决方案:

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

此可以更容易地作出反应UJS事件:

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

而不必写入原始原型或jQuery的code,可以使用导轨佣工。

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