2014-07-01 119 views
0

問題:如何訪問shortcutaction或其他局部變量的javascript:通過局部變量的匿名函數

相關:類似的問題,但沒有成功:

Java解決方案: 設置final改性劑,在匿名函數需要

目標源代碼變量:

//plugin.buttons is collection of button objects 
for (var i in plugin.buttons) { 
    var button = plugin.buttons[i]; 
    var icon = button.icon; 
    var text = button.text; 
    var shortcut = button.shortcut; 
    var action = button.action; //action is a function (or method) 

    if (shortcut != null && shortcut.length > 0) { 
     if ($.isFunction(action)) { 
      console.log(shortcut); //it's valid shortcut 
      //using jQuery hotkey plugin 
      $('div[contenteditable]').bind('keydown', shortcut, function() { 
       console.log(shortcut); //it's undefined 
       action.call(); //it's undefined also 
       return false; 
      }); 
     } 
    } 
} 
+0

如圖所示,因爲JS可以通過關閉...編輯到達那些瓦爾它應該只是工作:哎呦,在功能包住for循環,這是書中缺乏循環範圍的最古老的主要解決方法。 – dandavis

回答

2

你可以把它作爲event data

for (var i in plugin.buttons) { 
    var button = plugin.buttons[i]; 
    var icon = button.icon; 
    var text = button.text; 
    var shortcut = button.shortcut; 
    var action = button.action; //action is a function (or method) 

    if (shortcut != null && shortcut.length > 0) { 
     if ($.isFunction(action)) { 

      $('div[contenteditable]').on('keydown', {shortcut : shortcut}, function (e) { 

       console.log(e.data.shortcut); 

      }); 
     } 
    } 
} 

但是在這種情況下,真正的問題是在for循環中沒有特殊的作用域,因此在for循環中定義變量只是在每次迭代時覆蓋相同的變量,這就是爲什麼當事件處理程序將在稍後調用。

你必須在變量鎖定在一個新的範圍

for (var key in plugin.buttons) { 
    (function(i) { 
     var button = plugin.buttons[i]; 
     var icon = button.icon; 
     var text = button.text; 
     var shortcut = button.shortcut; 
     var action = button.action; //action is a function (or method) 

     if (shortcut != null && shortcut.length > 0) { 
      if ($.isFunction(action)) { 
       console.log(shortcut); //it's valid shortcut 
       //using jQuery hotkey plugin 
       $('div[contenteditable]').bind('keydown', shortcut, function() { 
        console.log(shortcut); //it's undefined 
        action.call(); //it's undefined also 
        return false; 
       }); 
      } 
     } 
    })(key); 
} 
+1

for循環的非範圍東西呢? – dandavis

+0

@dandavis - 哦,你說得對,for循環沒有範圍,所以每次迭代都會覆蓋變量。將它們作爲事件數據傳遞會解決這個問題,但是一個IIFE會更加合理,現在改變這個答案。 – adeneo

+0

你的第一個答案對我來說不起作用,因爲第二個參數必須是一個字符串來處理jQuery Hotkey。但你的第二個答案是很好的解決方案,並且運作良好謝謝。 – Behnam