2016-10-12 130 views
0

基本上我需要將參數傳遞給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 

好幫手功能我計算器上找到。

+0

WTH是'Object.size'? –

+0

在帖子正文中添加了Object.size。基本上它是一個計算對象大小的函數,我在stackoverflow上找到它。 –

回答

0

這爲我做的伎倆:

sound.once('load', ((key) => 
    () -> 
     self.sounds[key] = this 
      if Object.size(self.sounds) == self.totalFiles 
       if typeof callback == 'function' then callback() 
     )(key) 
    ) 
0

你的代碼中有一些問題,有可能隱藏真正的問題:

  • 不一致的縮進
  • self = this回調sound.once是FAT箭頭功能,這意味着該行 self.sounds[key] = this這和自是相同的
  • 包含大量不必要的大括號。
  • 在對象屬性定義中使用逗號不一致。

AFAIK實際的問題是,你想叫IIFE,你需要括號:

sound.once('load', ((key) => 
    (key) -> 
     self.sounds[key] = this 
     if Object.size(self.sounds) == self.totalFiles 
      if typeof callback == 'function' then callback() 
)(key)) 

除非你已經過度使用的名稱key。你有一個函數,你部分應用一個名爲key的參數,然後返回的函數接受一個名爲key的參數?這是什麼?

+0

我試過你的代碼,以前的異常消失了,但它返回的對象是空的。 –

+0

console.log this.sounds - > returns Object {undefined:o} –

+0

那是因爲密鑰未定義,請參閱我剛剛提供的更新。 –

相關問題