【问题标题】:Free standing function in coffeescript in Rails 3.2.8Rails 3.2.8 中咖啡脚本中的独立功能
【发布时间】:2012-10-01 10:11:25
【问题描述】:

我最近开始在我的 Rails 项目中大量使用咖啡脚本。

我很好奇您是如何制作独立式函数的。所以如果我这样做:

foo = ->
  alert("hello world")

编译成

(function() {
  var foo;

  foo = function() {
    return alert("hello world");
  };

}).call(this);

如何编译成

var foo;
foo = function(){
  return alert("hello world");
}

我希望能够调用使用link_to_function "foo"

【问题讨论】:

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


【解决方案1】:

实际上有几种方法可以实现这一点(cmets 中已经给出了一种方法)。

不使用闭包进行编译

这会将所有函数暴露给外部作用域。如果您使用可以控制构建过程的轻量级框架,这可能是一个选项。我不确定您是否能够在资产管道的上下文中使用,但在小型 sinatra 应用程序的上下文中效果很好。

coffee -b myfile.coffee

附加到全局对象

如果您知道您的目标是特定的运行时,例如浏览器,您可以使用全局窗口对象。

window.foo = -> alert("hello world")

这与 cmets 中的解决方案效果相同,因为目标是 Rails 环境。但是使用@this. 的糖会将它附加到this 目前的任何范围内。假设函数没有在回调或具有绑定上下文的内部对象中定义,它可能是窗口对象。

@foo = -> alert("hello world")

最好是创建自己的命名空间并以这种方式附加:

Mine ||= {}
Mine.foo = -> alert("hello world")
@Mine = Mine

CoffeeScript 类

或者使用 CoffeeScript 的类语法通过附加到原型本身来做同样的事情:

class @Mine
  @foo: -> alert("hello world") # called as Mine.foo() (notice the @ declaration)

在我们的 Rails 应用程序中,我们通常有一个定义命名空间的资产,也就是在 app/assets/javascripts 标题为 mine.coffee 的文件:

window.Mine ||= {}

然后在其他文件中我们可以要求该命名空间:

#= require mine

class Mine.MyOtherThing
  @foo: -> alert("hello world")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-06
    • 2011-11-08
    • 2013-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多