干燥js.erb文件(包括另一个js.erb文件) [英] DRY up js.erb files (include another js.erb file)

查看:97
本文介绍了干燥js.erb文件(包括另一个js.erb文件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Most of my js.erb files contains something like this at the bottom:

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

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

I would like to move these lines into a seperate file and then call that file from each of my js.erb files. Is something like that possible?

最好的问候. 阿斯伯恩·莫雷尔(

Best regards. Asbørn Morell

推荐答案

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

Yes, you may create an app/views/shared/_flash_messages.js.rjs partial, which you can then render from anywhere (e.g. from other rjs partials.)

我在这类应用程序中的处理方式如下:

My approach in these kinds of applications has been as follows:

  • 用于可能闪烁的非AJAX响应:

  • for non-AJAX responses that may have a flash:

  • 在布局中(例如layouts/application.erb),添加例如:
    render :partial => 'shared/flash_messages.html.erb'
  • in the layout (e.g. layouts/application.erb), add e.g.:
    render :partial => 'shared/flash_messages.html.erb'

对于可能还需要显示即时消息的AJAX响应,我添加了以下rjs代码:

for AJAX responses that may also need to display a flash message, I added the following rjs code:

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

在两个部分都需要渲染Flash的地方,然后根据需要调用flash.discard(:error)flash.discard(:notice).

Where the two partials do the necessary to render the flash, then call flash.discard(:error) or flash.discard(:notice) as appropriate.

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

示例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

这篇关于干燥js.erb文件(包括另一个js.erb文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆