基本上我需要將參數傳遞給coffeescript中的一個匿名函數,並且我已經用完了想法。如何將參數傳遞給coffeescript中的匿名函數?
這是我的代碼:
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
}
與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)
)
隨着callback.call()或callback.apply()我得到相同的結果,相同的編譯的JavaScript。我試圖在已經編譯過的javascript中添加(鍵)我需要它的地方,它按預期工作。
對象大小:
Object.size = (obj) ->
size = 0
for key in obj then if obj.hasOwnProperty(key) then size++
return size
好幫手功能我計算器上找到。
WTH是'Object.size'? –
在帖子正文中添加了Object.size。基本上它是一個計算對象大小的函數,我在stackoverflow上找到它。 –