Radu Dascălu Radu Dascălu - 1 month ago 7
CoffeeScript Question

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.

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():

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. I tried to add (key) where I needed it in already compiled javascript, and it worked as intended.

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.

Answer

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)
    )