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 );
} ) );
}
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
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
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With