Grundsätzlich muss ich in Coffeescript ein Argument an eine anonyme Funktion übergeben, und mir sind die Ideen ausgegangen.Wie übergeben Sie Argumente an anonyme Funktion in Coffeescript?
Dies ist mein 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
}
Der Code mit 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)
)
Mit callback.call() oder callback.apply() ich das gleiche Ergebnis zu erhalten, das gleiche kompilierte Javascript. Ich habe versucht, (Schlüssel), wo ich es in bereits kompiliertem Javascript brauchte, hinzuzufügen, und es hat wie beabsichtigt funktioniert.
Objektgröße:
Object.size = (obj) ->
size = 0
for key in obj then if obj.hasOwnProperty(key) then size++
return size
Ein guter Helfer Funktion fand ich auf Stackoverflow.
WTH ist 'Object.size'? –
Object.size im Post-Body hinzugefügt. Grundsätzlich ist es eine Funktion, die die Größe eines Objekts berechnet, ich habe es auf Stackoverflow gefunden. –