简体   繁体   中英

Trouble outputting the right variable value from within closure

I'm trying to use https://github.com/stepanvr/js-shortcuts jquery plugin for keyboard shortcuts. However I'm stuck with this problem. I define my shortcuts data in json data structure. Then I loop through these shortcuts and when the time comes to output the pressed shortcut the wrong one is reported. No matter which one shortcut I press the Ctrl+Shift+P combination is reported. I believe it is related to how JavaScript handles this handler function.

var data = {
    'name' : 'Eclipse (Java)',
    'version' : '1.0',
    'hotkeys' : {
        'Navigation' : {
            'Ctrl+Shift+R'      : 'Open / Search for resources, e.g. files',
            'Ctrl+Shift+T'      : 'Open / Search for Types',
            'Ctrl+E'            : 'Allows to select an editor',
            'Ctrl+F8'           : 'Shortcut for switching perspectives',
            'Alt+Left'          : 'Go to previous/ next editor position in history',
            'Ctrl+PageUp'       : 'Switch to previous/next editor',
            'F3'                : 'Go to the declaration of this variable',
            'Ctrl+Shift+P'      : 'Go to the matching bracket'
        }
    }
};

var verify = function(msg) {
    var node = document.getElementById('debug');
    node.innerHTML += msg + ' ';
};

$(document).ready(function() {
    for (var x in data.hotkeys.Navigation) {
        $.Shortcuts.add({
            type:'down',
            mask:x,
            handler:function () {
                verify(x);
            }
        });
    }
    $.Shortcuts.start();
});

Your problem is with the scope in setting up the callbacks the x variable is changing as the loop goes on, you have to wrap it in a closure like so:

  for (var x in data.hotkeys.Navigation) {
    (function(x){
      $.Shortcuts.add({
          type:'down',
          mask:x,
          handler:function () {
              verify(x);
          }
      });
    })(x);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM