[英]Accessing mutable variable in an event closure
我正在嘗試使用mousetrap Javascript 插件以類似的方式處理一些擊鍵,所以我想將它們編碼如下:
var keys = [ 'b', 'i', 'u'];
for (var i=0; i < 3; ++i) {
var iKey = keys[i];
var iKeyUpper = iKey.toUpperCase();
Mousetrap.bind(
[ 'command+' + iKey,
'command+' + iKeyUpper,
'ctrl+' + iKey,
'ctrl+' + iKeyUpper],
( function( e ) {
console.log( "you clicked: " + i );
} ) );
}
但是,顯然, i
是可變的。 但是,我不確定如何編寫一個我在響應中與事件參數競爭的閉包。 關於如何處理這種情況的建議?
如何在響應中與事件參數競爭的地方編寫閉包
在整個循環體周圍使用閉包(如@dandavis 所示),或者僅在處理程序周圍使用它:
…
Mousetrap.bind(
[ 'command+' + iKey,
'command+' + iKeyUpper,
'ctrl+' + iKey,
'ctrl+' + iKeyUpper],
(function(_i) { // of course you can use the name `i` again
return function( e ) {
console.log( "you clicked: " + _i );
};
})(i) // and pass in the to-be-preserved values
);
您需要將 i 變量包裝在本地范圍內,以便它不會與 for 循環中的“i”同步:
var keys = [ 'b', 'i', 'u'];
for (var i=0; i < 3; ++i) {
(function(i){
var iKey = keys[i];
var iKeyUpper = iKey.toUpperCase();
Mousetrap.bind(
[ 'command+' + iKey,
'command+' + iKeyUpper,
'ctrl+' + iKey,
'ctrl+' + iKeyUpper],
( function( e ) {
console.log( "you clicked: " + i );
} ) );
}(i));
}
另一種選擇是使用函數式 Array 方法,因為它們使用函數,所以總是有自己的范圍,並且它們本質上為您提供元素值和元素索引:
var keys = [ 'b', 'i', 'u'];
keys.map(function(iKey, i){
var iKeyUpper = iKey.toUpperCase();
Mousetrap.bind(
[ 'command+' + iKey,
'command+' + iKeyUpper,
'ctrl+' + iKey,
'ctrl+' + iKeyUpper],
function( e ) {
console.log( "you clicked: " + i );
}); // end bind()
}); // end map()
第二個示例將在 IE9+ 中開箱即用,但您可以使用簡單的插入式數組方法兼容包使其在任何地方工作,通常包含在 IE 墊片中...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.