繁体   English   中英

Rails 4资产管道树中的Javascript函数

[英]Javascript functions in the rails 4 asset pipeline tree

当我将JavaScript函数放入Rails Asset Pipeline清单中时,我试图通过Chrome控制台使用JavaScript函数。 这是我创建和设置简单的Rails 4.2.4 App所采取的步骤

$ rails new JavascriptExample
$ cd JavascriptExample
$ rails g scaffold Bear name:string
$ rake db:migrate

然后,我编辑app/assets/javascripts/bears.coffee并添加控制台日志和功能。

console.log("asset pipeline sucks")
square = (x) -> x * x

然后我启动服务器

$ rails s

我访问了localhost:3000/bears ,在Chrome控制台中,我看到第一行代码已经起作用。 但是,当我尝试命令square(5); 在控制台中,我收到一个错误: Uncaught ReferenceError: square is not defined(…)

当此函数明确加载到application.js时,为什么不能这样做呢?

这是您的coffeescript被编译为javascript的内容

(function() {
  var square;

  console.log("asset pipeline sucks");

  square = function(x) {
    return x * x;
  };
}).call(this);

这个the var keyword is reserved in CoffeeScript, and will trigger a syntax error if used. Local variables are created implicitly by default the var keyword is reserved in CoffeeScript, and will trigger a syntax error if used. Local variables are created implicitly by default ,因此按您的期望在全局范围内不可用

为了使它起作用,我们可以改为执行以下操作:

console.log("asset pipeline sucks")
@square = (x) -> x * x

请注意,我们有@ ,现在编译的javascript将是:

(function() {
  console.log("asset pipeline sucks");

  this.square = function(x) {
    return x * x;
  };

}).call(this);

暂无
暂无

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

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