[英]How to pass arguments to anonymous function in coffeescript?
Basically I need to pass an argument to an anonymous function in coffeescript, and I've ran out of ideas. 基本上,我需要将参数传递给coffeescript中的匿名函数,而我的想法已经用完了。
This is my code: 这是我的代码:
audio = {
sounds: {},
sources: [{
wind: 'sounds/wind.mp3'
}],
load: (callback) ->
this.totalFiles = Object.size(this.sources[0])
for key of this.sources[0]
sound = new Howl({ src: [this.sources[0][key]] })
self = this
sound.once('load', (key) =>
(key) ->
self.sounds[key] = this
if Object.size(self.sounds) == self.totalFiles
if typeof callback == 'function' then callback()
(key)) <- THIS ARGUMENT PASSING DOES NOT COMPILE CORRECTLY
loop: (name) ->
this.sounds[name].loop(true)
console.log this.sounds
}
The code with callback.call(): 带callback.call()的代码:
load: (callback) ->
this.totalFiles = Object.size(this.sources[0])
for key of this.sources[0]
sound = new Howl({ src: [this.sources[0][key]] })
self = this
sound.once('load', (key) =>
callback.call(() ->
self.sounds[key] = this
if Object.size(self.sounds) == self.totalFiles
if typeof callback == 'function' then callback()
, key)
)
With callback.call() or callback.apply() I get the same result, the same compiled javascript. 使用callback.call()或callback.apply(),我得到相同的结果,相同的已编译javascript。 I tried to add (key) where I needed it in already compiled javascript, and it worked as intended. 我试图在已经编译的javascript中将(key)添加到需要的地方,并且按预期工作。
Object size: 物件大小:
Object.size = (obj) ->
size = 0
for key in obj then if obj.hasOwnProperty(key) then size++
return size
A good helper function I found on stackoverflow. 我在stackoverflow上找到了一个很好的辅助函数。
Your code has some issues that are likely hiding the real problem: 您的代码中存在一些可能隐藏实际问题的问题:
self = this
the callback to sound.once
is a fat arrow function, meaning that the line self.sounds[key] = this
this and self are the same self = this
到sound.once
的回调sound.once
是一个sound.once
箭头函数,表示self.sounds[key] = this
this和self相同 AFAIK the actual problem is that you're trying to call an IIFE, and you need parens: AFAIK实际的问题是您试图调用IIFE,并且需要parens:
sound.once('load', ((key) =>
(key) ->
self.sounds[key] = this
if Object.size(self.sounds) == self.totalFiles
if typeof callback == 'function' then callback()
)(key))
Except that you've over-used the name key
. 除非您过度使用了name key
。 You've got a function that you're partially applying with a parameter named key, and then the returned function also takes a parameter named key? 您有一个要部分使用名称为key的参数的函数,然后返回的函数也需要一个名为key的参数? Which is it? 哪有
This did the trick for me: 这对我有用:
sound.once('load', ((key) =>
() ->
self.sounds[key] = this
if Object.size(self.sounds) == self.totalFiles
if typeof callback == 'function' then callback()
)(key)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.