Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing mutable variable in an event closure

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?

like image 894
jedierikb Avatar asked Jun 20 '13 15:06

jedierikb


1 Answers

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
    );
like image 154
Bergi Avatar answered Sep 29 '22 07:09

Bergi