0

I'm coding a TinyMCE plugin for Wordpress and I've just run in to a little issue with how I'm approaching things. Basically, I'm using a loop which relies on a counter i. The loop is responsible for building an array with TinyMce details in it. One of those things is a function call which is passed the i counter.

But of course, by the time that the click actually registers, that counter is always at it's maximum. I solved this temporarily by using let in my loop. Here's the loop:

for(let i = 0; i <= pmsb.config.length - 1; i++) {
    menu[i] = {
        text: pmsb.config[i].title,
        onclick: function() {
            open_dialog(i);
        }
    }
}

I'm aware that let isn't well supported and with this being a Wordpress plugin, I've no real control over the browsers which my target audience will use.

So in the case of the above loop - how do I make the function call receive the correct number (as let does)?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0Neji
  • 1,038
  • 1
  • 14
  • 36

1 Answers1

3

Rather than a for loop, use forEach instead - the resulting callback will automatically receive the index as a parameter that will be correctly bound in scope:

pmsb.config.forEach(function(config, i) {
    menu[i] = {
        text: config.title,
        onclick: function() {
            open_dialog(i);
        }
    }
});

If (as appears likely) there's a one-to-one mapping from pmsb.config[i] to menu[i] you can better still use .map instead of forEach:

var menu = pmsb.config.map(function(config, i) {
    return {
        text: config.title,
        onclick: function() {
             open_dialog(i);
        }
    }
});
Alnitak
  • 334,560
  • 70
  • 407
  • 495