【问题标题】:Custom coffeescript in Rails asset pipelineRails 资产管道中的自定义咖啡脚本
【发布时间】:2013-01-09 14:50:40
【问题描述】:

我在 app/assets/javascripts/custom.js 中创建了一个带有函数定义的小型自定义 javascript 文件

round_number = function(num, dec) {
  return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
};

应用程序运行良好,因为文件已插入资产管道。 然后,出于学习的目的,我将其转换为 coffescript:

round_number = (num, dec) ->
  Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec)

但令我惊讶的是,该应用程序无法正常工作。 我在 localhost:3000/assets/custom.js 中检查了 coffescript 被翻译成:

(function() {
  var round_number;

  round_number = function(num, dec) {
    return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
  };

}).call(this);

为什么要进行额外的包装,导致该功能在我需要的地方不可用?

如果我不是在 custom.js.coffee 文件中插入 coffescript 函数,而是在 app/assets/javascripts/orders.js.coffee(其中 Order 是我的类)中插入,它将被翻译成预期的 javascript。

我想将共享的 javascript 函数放在一个单独的文件中,因为它更有序。 我知道,即使我将函数放在 orders.js.coffee 中,它也会在整个应用程序中可用(这就是我想要完成的),但我很困惑。 有没有我在这里遗漏的最佳实践?

--- 编辑 ---

我从"Can't find variable" error with Rails 3.1 and Coffeescript了解到

我认为我会以这种方式组织我的 Rails 应用程序:

1) 创建文件 app/assets/javascripts/global.js.coffee 以包含所有全局变量和函数。在这个文件里放一行

window.Global ||= {}

定义一个全局命名空间。将函数定义为

Global.function_name = (arguments) ->
  ...

2) 调用函数:

Global.function_name(arguments)

【问题讨论】:

    标签: ruby-on-rails coffeescript asset-pipeline


    【解决方案1】:

    是的,如果您想要全局可用的东西,请将其设置为 window 上的属性。 Coffeescript 编译器将您的代码包装在一个匿名函数中,以防止意外的名称冲突。

    【讨论】:

      猜你喜欢
      • 2013-08-26
      • 2013-04-24
      • 1970-01-01
      • 2016-02-09
      • 2012-06-07
      • 1970-01-01
      • 2013-04-28
      • 2013-09-07
      • 1970-01-01
      相关资源
      最近更新 更多