you need to wrap the variable i in the local scope so that it does not synchronize with the "i" in the for loop:
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)); }
another alternative is to use Array functional methods, which, since they use functions, always have their own scope, and they provide you with the actual value of the element and element:
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 ); });
The 2nd example will work out of the box in IE9 +, but you can make it work anywhere with the simple Array package package, usually included in IE gaskets ...
source share