0

我正在使用 Rails 和 CoffeeScript,需要在:coffeescript标签下的 Haml 文件中定义和调用函数。

我尝试使用此代码,但它会生成“未定义tabsOnLoadMethod”错误:

:coffeescript
  $ ->
    tabsOnLoadMethod ->
      alert 'hello team'

我使用tabsOnLoadMethod();.

错误:

ReferenceError: tabsOnLoadMethod is not defined

这哪里出错了?

4

1 回答 1

1
tabsOnLoadMethod ->
  alert 'hello team'

编译为

tabsOnLoadMethod(function() {
  return alert('hello team');
});

我认为您正在尝试调用一个函数,而不是向它传递另一个函数/回调

tabsOnLoadMethod = ->
  alert 'hello team'

如果您想通过 html 调用此方法(例如 onclick 侦听器),则必须将其附加到this(使用@)或window

@tabsOnLoadMethod = ->
  alert 'hello team'

或者

window.tabsOnLoadMethod = ->
  alert 'hello team'
于 2020-02-20T14:43:49.930 回答