【问题标题】:Calling CoffeeScript method defined in another file form within an erb template调用 erb 模板中另一个文件形式中定义的 CoffeeScript 方法
【发布时间】:2012-04-16 14:34:27
【问题描述】:

难道我不能在 erb 模板中调用这个 CoffeeScript 方法吗?它不起作用,但似乎应该这样做。

setup.js.coffee

class SetupStepTwo

  include @

  constructor: ->
    @resetView()

  resetView : ->
    console.log('cool');

window.ns1.SetupStepTwo = SetupStepTwo

$ ->
  new SetupStepTwo()

update.js.erb

window.ns1.SetupStepTwo.resetView();

【问题讨论】:

  • 我认为这在理论上应该可行。由于include @ 行,您的示例将无法运行。 include 是否在您的代码中的其他地方定义?
  • 是的,我在别处定义了“包含”。这不会引起任何问题。

标签: ruby-on-rails coffeescript erb


【解决方案1】:

您的 SetupStepTwo 类有一个名为 resetViewinstance 方法,但您试图将其称为 class 方法(或至少作为(Java|Coffee)Script) 中的类方法,当你这样说时:

window.ns1.SetupStepTwo.resetView();

如果你真的想使用resetView 作为类方法,那么你的类应该看起来更像这样:

class SetupStepTwo
  constructor: ->
    @constructor.resetView()

  @resetView : ->
    console.log('cool')

@resetView 上的 @ 构成一个类方法,@constructor 或多或少类似于 Ruby 中的 self.class

演示:http://jsfiddle.net/ambiguous/eDdmd/

如果您希望 resetView 成为实例方法,那么您需要替换它:

window.ns1.SetupStepTwo.resetView();

SetupStepTwo 的实例上调用resetView

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2016-07-06
    • 2014-07-06
    • 2016-10-12
    • 2016-11-16
    相关资源
    最近更新 更多