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

per*_*nce 18 ruby-on-rails ruby-on-rails-3

我在我的application.js中放了以下函数:

function test() {
  alert("See Me")
}
Run Code Online (Sandbox Code Playgroud)

教室/ _new_small.html.haml:

:javascript
  alert('test');
  test();
Run Code Online (Sandbox Code Playgroud)

在我的application.html.haml中我使用以下内容:

= javascript_include_tag 'application'
Run Code Online (Sandbox Code Playgroud)

我得到一个test is not defined在我的萤火控制台错误.测试函数是否应该在项目范围内可用,因为它在application.js文件中?谢谢

编辑:我正在通过javascript渲染页面.这会影响它吗?

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

m4t*_*m4t 27

假设您正在使用资产管道和coffeescript:不要在application.js中编写代码

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

然后在你的需要它 application.js

//= require jquery
//= require jquery_ujs

//= require_tree ./application
Run Code Online (Sandbox Code Playgroud)

创建一个咖啡文件(例如: app/assets/javascripts/application/my_feature.js.coffee

@test = ->
  alert('Hello world')
Run Code Online (Sandbox Code Playgroud)

咖啡输出:

(function() {

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

}).call(this);
Run Code Online (Sandbox Code Playgroud)

最好使用命名空间:

@myGreatFeature =
  test: ->
    alert('Hello world')
Run Code Online (Sandbox Code Playgroud)

或者根据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')
Run Code Online (Sandbox Code Playgroud)

然后你可以myGreatFeature.test()到处打电话