accessing mutable variable in an event closure

对着背影说爱祢 提交于 2019-12-23 09:30:17

问题


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?


回答1:


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
    );



回答2:


you need to wrap the i variable in a local scope so that it won't sync 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));
    }

the other alternative is to use functional Array methods, which since they use functions, always have their own scope, and they provide the element value and element index to you intrinsically:

 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()

the 2nd example will work out of the box in IE9+, but you can make it work anywhere with a simple drop-in Array method compat pack, usually included in IE shims...



来源:https://stackoverflow.com/questions/17218075/accessing-mutable-variable-in-an-event-closure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!