简体   繁体   English

有没有更好的方法在Ruby on Rails上做不引人注目的JavaScript?

[英]Is there a better way to do Unobtrusive JavaScript on Ruby on Rails?

The way I found to put javascript on a separated file without the use of RJS or ERB was using an instance variable at javascript_include_tag helper. 我发现在不使用RJS或ERB的情况下将javascript放在单独的文件上的方法是在javascript_include_tag帮助器中使用实例变量。

<%= javascript_include_tag @extra_head_content if !@extra_head_content.nil? %>

Then I put the name of the current javascript file at the instance variable from the controller; 然后我将当前javascript文件的名称放在控制器的实例变量中;

def index
    @extra_head_content = "test"
#...
end

And at my javascript file (test.js) I add some code. 在我的javascript文件(test.js)中,我添加了一些代码。

 $j(function() {
  alert("test");
 })

Is there any "better" way to do this? 有没有“更好”的方法来做到这一点? Any convention that I'm missing? 我遗失的任何约定?

I found a lot of information for UJS to XHR(AJAX) but nothing abot the conventions for a simple thing like " unobtrusive (document).ready" 我找到了很多关于UJS到XHR(AJAX)的信息,但是对于像“unobtrusive(document).ready”这样简单的事情没有任何约定。

I'm using rails 3-0-9. 我正在使用rails 3-0-9。

I do something like this: 我做这样的事情:

in ApplicationHelper: 在ApplicationHelper中:

def javascript(file)
  content_for(:javascript_at_head){ javascript_include_tag file }
end

in layouts/application.html.erb 在layouts / application.html.erb中

<%= yield(:javascript_at_head) %>

and in another template: 在另一个模板中:

<% javascript :test %>

为什么不使用content_foryield

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM