干掉js.erb文件(包括另一个js.erb文件)

atm*_*ell 8 jquery ruby-on-rails

我的大多数js.erb文件底部都包含这样的内容:

$("#flash_message").html("<%= escape_javascript(content_tag(:p, flash[:note], :class => "note")) %>");
$("#flash_message").fadeOut(2000);
$("#loading").remove();
Run Code Online (Sandbox Code Playgroud)

我想将这些行移动到一个单独的文件中,然后从我的每个js.erb文件中调用该文件.有可能吗?

最好的祝福.AsbørnMorell

vla*_*adr 7

是的,您可以创建一个app/views/shared/_flash_messages.js.rjs部分,然后可以从任何地方(例如,从其他rjs部分)进行渲染.

我在这些应用程序中的方法如下:

  • 对于可能有闪存的非AJAX响应:

    • 在布局(例如layouts/application.erb)中,添加例如:
      render :partial => 'shared/flash_messages.html.erb'
  • 对于可能还需要显示flash消息的AJAX响应,我添加了以下rjs代码:

    • 在每个rjs响应中(例如controller/action.js.rjs),添加例如:
      render :partial => 'shared/flash_messages.js.rjs'

如果两个部分做了渲染闪光所必需的,那么请打电话flash.discard(:error)flash.discard(:notice)酌情.

样本app/views/shared/flash_messages.html.erb文件:

<% if flash[:error] %>
<div id="flash_message" class="error"><%= h(flash[:error]) %></div>
<% flash.discard(:error) %>
<% elsif flash[:notice] %>
<div id="flash_message" class="notice"><%= h(flash[:notice]) %></div>
<% flash.discard(:notice) %>
<% else %>
<div id="flash_message" style="display: none;" />
<% end %>
Run Code Online (Sandbox Code Playgroud)

样本app/views/shared/flash_messages.html.rjs文件:

if !flash[:error].blank?
  page['flash_message'].
    replace_html(flash[:error]).
    removeClassName('notice').
    addClassName('error').
    show()
else
  page['flash_message'].
    replace_html(flash[:notice]).
    removeClassName('error').
    addClassName('notice').
    show()
end
Run Code Online (Sandbox Code Playgroud)