1

In following code I try to create several handler functions that must invoke different functions stored in an array of functions ('buttonHandlers'). This array is part of the outer scope:

buttonJson = {};
for (i = 0; i < buttonNames.length; i++) {
    customHandler = buttonHandlers[i];
    buttonJson[buttonNames[i]] = function() {
        customHandler.apply();
        $('#msg-dialog-confirm').dialog("close");
        $('body').remove('#msg-dialog-confirm');
        ...
    };
}

The code above results in handler functions that invoke the very last array element of the functions array ('buttonHandlers'). I want each handler function to invoke only the associated function specified by the concerning array index. How can I achieve this?

PAX
  • 1,056
  • 15
  • 33
  • Try with `buttonJson[buttonNames[i]] = function(customHandler) {` – juvian May 24 '14 at 17:01
  • It doesn't do the trick. Possibly, this hint is too short. Anyway, I need to pass the function to this parameter. – PAX May 24 '14 at 17:26

1 Answers1

2

customHandler is a global, you're overwriting it on each iteration, you should create a new scope to lock in the value

buttonJson = {};
for (i = 0; i < buttonNames.length; i++) {
    (function(button) {
        buttonJson[button] = function() {
            button.apply();
            $('#msg-dialog-confirm').dialog("close");
            $('body').remove('#msg-dialog-confirm');
            ...
        };
    })(buttonHandlers[i]);
}
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Thanks! This works like a charm! Additionally, we also have to pass the value from `buttonNames[i]` and to use it as key value: `buttonJson[text]`. – PAX May 24 '14 at 17:19