2016-01-06 58 views
1

我试图得到一个功能到CoffeeScript的的CoffeeScript不是在资产管道的工作

如果我用纯JavaScript资产管道,

mymodel.js

function restrictPlayback(event) { 
    // Trying to stop the player if it goes above 1 second 
    if (event.currentTime > 10) { 
    event.pause(); 
    event.currentTime = 0 
    } 
} 

编译没有问题并且该功能起作用。

如果我把以下内容:

mymodel.js.coffee

restrictPlayback = (event) -> 

    # Trying to stop the player if it goes above 10 seconds 
    if event.currentTime > 10 
    event.pause() 
    event.currentTime = 0 

我收到以下错误

Uncaught ReferenceError: restrictPlayback is not defined 

我在做什么错?

+0

我不写Coffeescript,但我把你的JS放入[js2coffee](http://js2.coffee/),它在函数结尾处有一个return语句。它也取决于你想要访问'restrictPlayback'的地方。 –

+1

该问题与您给我们的代码无关。你的CoffeeScript编译得很好。 – 2016-01-06 16:25:11

+0

你在哪里调用'restrictPlayback'?如果在宣布之前,这可能是问题的原因 –

回答

1

我怀疑你正在定义函数,然后期望它具有全局范围(即可以从任何地方使用)。

默认情况下,Coffeescript将编译代码包装到Immediately Invoked Function Expressions (IIFEs)中,所以您声明的函数只在Coffeescript文件的范围内有效。

您可以通过在编译时使用-b标志来让Coffeescript停止在IIFE中进行包装,尽管学习使用Coffeescript的方式是更好的做法。