如何使用 ":coffeescript" 标记在 Haml 中定义 CoffeeScript 方法



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

我尝试使用此代码,但它生成了一个"未定义的tabsOnLoadMethod"错误:

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

我使用tabsOnLoadMethod();调用了该方法。

错误:

ReferenceError: tabsOnLoadMethod is not defined

这哪里出了问题?

tabsOnLoadMethod ->
alert 'hello team'

被编译为

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

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

tabsOnLoadMethod = ->
alert 'hello team'

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

@tabsOnLoadMethod = ->
alert 'hello team'

window.tabsOnLoadMethod = ->
alert 'hello team'

最新更新