如何创建一个允许在RoR 3.2+中全局访问其功能的js文件?

时间:2013-02-12 01:14:50

标签: ruby-on-rails-3

我在我的application.js文件中创建了一个javascript函数用于测试目的,但是当我在我的视图文件中使用该函数内联时,我无法访问它。

应用程序/资产/ application.js中:

//= require jquery
//= require jquery_ujs
//= require_tree .

$(document).ready(function() {
  function test() {
    alert('test');
  }
}

视图/布局/ application.html.haml

:javascript
  test(); // gives me a Uncaught ReferenceError: test is not defined error

1 个答案:

答案 0 :(得分:0)

$(document).ready(function() {
  test = function() {
    console.log("foo");
  }
});


// wait for document ready
$(document).ready(function() {
  test();
});

$(document).ready(function() {
  window.test();
});

这也将失败

$(document).ready(function() {
  var test = function() {
    console.log("foo");
  }
});

这也应该提供一些好的阅读var functionName = function() {} vs function functionName() {}