在事件关闭中访问可变变量 [英] accessing mutable variable in an event closure
本文介绍了在事件关闭中访问可变变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用捕鼠器 javascript插件以类似方式处理一些关键笔划,因此我想要对它们进行编码如下:
I am trying to use the mousetrap javascript plugin to handle some key strokes in a similar fashion, so I thought to code them up as follows:
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
是可变的。但是,我不知道如何写一个闭包,我在竞争事件参数的响应。关于如何处理此情况的建议?
But, obviously, i
is mutable. However, I am not sure how to write a closure where I am competing the event parameter in the response. Suggestions on how to handle this situation?
推荐答案
如何写闭包,事件参数
how to write a closure where I am competing the event parameter in the response
使用闭包围绕整个循环体(如@dandavis)演示),或仅使用它处理程序:
Use a closure either around the whole loop body (as @dandavis) demonstrated), or use it only around the handler:
…
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
);
这篇关于在事件关闭中访问可变变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文