如何创建在Ruby on Rails中可用的项目范围内的javascript函数?

时间:2023-02-06 07:56:30

I put the following function in my application.js:

我在我的应用程序中添加了如下函数:

function test() {
  alert("See Me")
}

classrooms/_new_small.html.haml:

教室/ _new_small.html.haml:

:javascript
  alert('test');
  test();

In my application.html.haml I'm using the following:

在我application.html。haml我用的是:

= javascript_include_tag 'application'

I'm getting a test is not defined error in my firebug console. Isn't the test function supposed to be available project-wide because its in the application.js file? Thanks

我在我的firebug控制台中得到的测试没有定义错误。测试函数不应该在项目范围内可用,因为它在应用程序中。js文件?谢谢

edit: I'm rendering the page via javascript. Would that affect it?

编辑:我正在通过javascript呈现页面。会影响吗?

$('#test_container').html("<%= escape_javascript(render :partial => 'classrooms/new_small') %>");

7 个解决方案

#1


25  

Assuming you are using asset pipeline & coffeescript: Don't write code in application.js

假设您正在使用资产管道& coffeescript:不要在应用程序中编写代码。

In order to keep clean structure, create a folder (eg: application) in app/assets/javascripts

为了保持清晰的结构,在app/assets/javascript中创建一个文件夹(如:application)

then require it in your application.js

然后在你的应用程序中要求它

//= require jquery
//= require jquery_ujs

//= require_tree ./application

Create a coffee file (eg: app/assets/javascripts/application/my_feature.js.coffee

创建一个咖啡文件(例如:应用程序/资产/java脚本/应用程序/my_feature.js.coffee)。

@test = ->
  alert('Hello world')

Coffee output:

咖啡输出:

(function() {

  this.test = function() {
    return alert('Hello world');
  };

}).call(this);

It's preferable to use namespaces:

最好使用名称空间:

@myGreatFeature =
  test: ->
    alert('Hello world')

or according to the coffeescript FAQ, you could write

或者根据coffeescript FAQ,你可以写

namespace = (target, name, block) ->
  [target, name, block] = [(if typeof exports isnt 'undefined' then exports else window), arguments...] if arguments.length < 3
  top    = target
  target = target[item] or= {} for item in name.split '.'
  block target, top

namespace 'myGreatFeature', (exports) ->
  exports.test = ->
    alert('Hello world')

then you can call myGreatFeature.test() everywhere

然后可以在任何地方调用greatmyfeature.test ()

#2


1  

I tried this without an issue. Here's how I did it.

我试过没有问题。我是这样做的。

// application.js

/ / application.js

var test=function(){
  alert("hello");
}

// in a view, whichever one, i have a content_for :additional_javascripts

//在一个视图中,无论哪个视图,我都有一个content_for:additional_javascript

<% content_for :additional_javascripts do %>
  <%= javascript_tag do %>
    test();
  <% end %>
<% end %>

// in application layout

/ /在应用程序的布局

<%= javascript_include_tag "application" %>
<%= yeild(:additional_javascripts) %>

Furthermore, if I want to alert this dynamically later on I could append it to the page and call it then, or put it in a click listener or something.

此外,如果我想在稍后动态地提醒它,我可以将它附加到页面上,然后调用它,或者将它放在单击监听器或其他东西中。

I like the syntax var functionName = function(){...} because it properly scopes the method. Also, because of the way javascripts are compiled through the asset pipeline, adding the ; at the end of every executed line is very important.

我喜欢var functionName = function(){…}因为它正确地作用域了方法。此外,由于javascript是通过资产管道编译的,所以添加了;在每一行的末尾都是非常重要的。

This also worked for me as far as loading the script dynamically and calling it from anywhere in the page:

这对我来说也适用于动态加载脚本并从页面的任何地方调用它:

$("#click_me").live("click", function(){
  $("<script />").text("test();").appendTo("body");
});

And in the page I had a simple link.

在页面中我有一个简单的链接。

<a href="#" id="click_me">click</a>

#3


0  

You're probably thinking of the line

你可能在想这条线

= javascript_include_tag "application"

rather than

而不是

= stylesheet_link_tag 'application', :media => 'all'

If the former is missing, your javascript won't be included.

如果缺少前者,则不包含javascript。

#4


0  

Try using:

尝试使用:

<%= javascript_include_tag :all %>

in your application.html.erb file

在你application.html。erb文件

#5


0  

I noticed your function test() is indented, which suggests it is nested. If you define a function in the scope of another function, it will not be available outside of it.

我注意到您的函数test()是缩进的,这表明它是嵌套的。如果在另一个函数的范围内定义一个函数,那么它在该函数之外是不可用的。

For example this should work, using jQuery:

例如,使用jQuery:

function test() { /* do something */ }

// another file or inline script

$(function() {
   test();
});

But this won't

但这不会

(function() {
   function test() {}
})();

// another file

test(); // undefined

#6


0  

Simple solution, remove escape_javascript, but it's dangerous see Why escape_javascript before rendering a partial? . Currently you want to execute

简单的解决方案,删除escape_javascript,但是在呈现部分之前,看看为什么要使用escape_javascript ?。当前您希望执行

$('#test_container').html("<script>
//<![CDATA[
 alert('test');
 test();
//]]>
</script>

which is converted into

这是转化为

$('#test_container').html("<script>\n  //<![CDATA[\n    alert(\'test\');\n    test();\n  //]]>\n<\/script>\n");

How do i solve this problem ?

i will include project_wide.js in app/assets/javascripts/ and then tell application.js to include my file .

我将包括project_wide。在app/assets/javascript /然后告诉应用。包含我的文件。

//= require project_wide

Be sure to put the above line after

一定要把上面的线放在后面

//= require jquery
//= require jquery_ujs

Now, whatever i put in app/assets/javascripts/project_wide.js it will shamelessly appear in whole project except the files which are in public/ folder . In this file, i will put everything which i want to execute .

现在,不管我在app/assets/javascript /project_wide放了什么。在整个项目中,除了在公共/文件夹中的文件之外,它将无耻地出现。在这个文件中,我将把我想要执行的所有东西都放入其中。

Follow common practice

Currently,you are adding javascript directly inside classrooms/_new_small.html.haml which is uncommon. Mostly , rails developer put such things in assets/javascripts/*.js or call content_for :javascript_custom block in views , which is added in layout file by yield :javascript_custom

目前,您正在直接在classroom /_new_small.html中添加javascript。haml少见。大多数情况下,rails开发人员会把这些东西放在assets/javascript /*中。在视图中调用content_for:javascript_custom块,由yield:javascript_custom在布局文件中添加

#7


0  

put all those javascript functions in application.js file and include <%= javascript_include_tag 'application' %> in head tag of your layout file

将所有这些javascript函数放到应用程序中。js文件,并在布局文件的head标签中包含<%= javascript_include_tag 'application' %>。

#1


25  

Assuming you are using asset pipeline & coffeescript: Don't write code in application.js

假设您正在使用资产管道& coffeescript:不要在应用程序中编写代码。

In order to keep clean structure, create a folder (eg: application) in app/assets/javascripts

为了保持清晰的结构,在app/assets/javascript中创建一个文件夹(如:application)

then require it in your application.js

然后在你的应用程序中要求它

//= require jquery
//= require jquery_ujs

//= require_tree ./application

Create a coffee file (eg: app/assets/javascripts/application/my_feature.js.coffee

创建一个咖啡文件(例如:应用程序/资产/java脚本/应用程序/my_feature.js.coffee)。

@test = ->
  alert('Hello world')

Coffee output:

咖啡输出:

(function() {

  this.test = function() {
    return alert('Hello world');
  };

}).call(this);

It's preferable to use namespaces:

最好使用名称空间:

@myGreatFeature =
  test: ->
    alert('Hello world')

or according to the coffeescript FAQ, you could write

或者根据coffeescript FAQ,你可以写

namespace = (target, name, block) ->
  [target, name, block] = [(if typeof exports isnt 'undefined' then exports else window), arguments...] if arguments.length < 3
  top    = target
  target = target[item] or= {} for item in name.split '.'
  block target, top

namespace 'myGreatFeature', (exports) ->
  exports.test = ->
    alert('Hello world')

then you can call myGreatFeature.test() everywhere

然后可以在任何地方调用greatmyfeature.test ()

#2


1  

I tried this without an issue. Here's how I did it.

我试过没有问题。我是这样做的。

// application.js

/ / application.js

var test=function(){
  alert("hello");
}

// in a view, whichever one, i have a content_for :additional_javascripts

//在一个视图中,无论哪个视图,我都有一个content_for:additional_javascript

<% content_for :additional_javascripts do %>
  <%= javascript_tag do %>
    test();
  <% end %>
<% end %>

// in application layout

/ /在应用程序的布局

<%= javascript_include_tag "application" %>
<%= yeild(:additional_javascripts) %>

Furthermore, if I want to alert this dynamically later on I could append it to the page and call it then, or put it in a click listener or something.

此外,如果我想在稍后动态地提醒它,我可以将它附加到页面上,然后调用它,或者将它放在单击监听器或其他东西中。

I like the syntax var functionName = function(){...} because it properly scopes the method. Also, because of the way javascripts are compiled through the asset pipeline, adding the ; at the end of every executed line is very important.

我喜欢var functionName = function(){…}因为它正确地作用域了方法。此外,由于javascript是通过资产管道编译的,所以添加了;在每一行的末尾都是非常重要的。

This also worked for me as far as loading the script dynamically and calling it from anywhere in the page:

这对我来说也适用于动态加载脚本并从页面的任何地方调用它:

$("#click_me").live("click", function(){
  $("<script />").text("test();").appendTo("body");
});

And in the page I had a simple link.

在页面中我有一个简单的链接。

<a href="#" id="click_me">click</a>

#3


0  

You're probably thinking of the line

你可能在想这条线

= javascript_include_tag "application"

rather than

而不是

= stylesheet_link_tag 'application', :media => 'all'

If the former is missing, your javascript won't be included.

如果缺少前者,则不包含javascript。

#4


0  

Try using:

尝试使用:

<%= javascript_include_tag :all %>

in your application.html.erb file

在你application.html。erb文件

#5


0  

I noticed your function test() is indented, which suggests it is nested. If you define a function in the scope of another function, it will not be available outside of it.

我注意到您的函数test()是缩进的,这表明它是嵌套的。如果在另一个函数的范围内定义一个函数,那么它在该函数之外是不可用的。

For example this should work, using jQuery:

例如,使用jQuery:

function test() { /* do something */ }

// another file or inline script

$(function() {
   test();
});

But this won't

但这不会

(function() {
   function test() {}
})();

// another file

test(); // undefined

#6


0  

Simple solution, remove escape_javascript, but it's dangerous see Why escape_javascript before rendering a partial? . Currently you want to execute

简单的解决方案,删除escape_javascript,但是在呈现部分之前,看看为什么要使用escape_javascript ?。当前您希望执行

$('#test_container').html("<script>
//<![CDATA[
 alert('test');
 test();
//]]>
</script>

which is converted into

这是转化为

$('#test_container').html("<script>\n  //<![CDATA[\n    alert(\'test\');\n    test();\n  //]]>\n<\/script>\n");

How do i solve this problem ?

i will include project_wide.js in app/assets/javascripts/ and then tell application.js to include my file .

我将包括project_wide。在app/assets/javascript /然后告诉应用。包含我的文件。

//= require project_wide

Be sure to put the above line after

一定要把上面的线放在后面

//= require jquery
//= require jquery_ujs

Now, whatever i put in app/assets/javascripts/project_wide.js it will shamelessly appear in whole project except the files which are in public/ folder . In this file, i will put everything which i want to execute .

现在,不管我在app/assets/javascript /project_wide放了什么。在整个项目中,除了在公共/文件夹中的文件之外,它将无耻地出现。在这个文件中,我将把我想要执行的所有东西都放入其中。

Follow common practice

Currently,you are adding javascript directly inside classrooms/_new_small.html.haml which is uncommon. Mostly , rails developer put such things in assets/javascripts/*.js or call content_for :javascript_custom block in views , which is added in layout file by yield :javascript_custom

目前,您正在直接在classroom /_new_small.html中添加javascript。haml少见。大多数情况下,rails开发人员会把这些东西放在assets/javascript /*中。在视图中调用content_for:javascript_custom块,由yield:javascript_custom在布局文件中添加

#7


0  

put all those javascript functions in application.js file and include <%= javascript_include_tag 'application' %> in head tag of your layout file

将所有这些javascript函数放到应用程序中。js文件,并在布局文件的head标签中包含<%= javascript_include_tag 'application' %>。