this.config = {
source: psource,
_events: [
'value1',
'value2',
'value3'
]
};
// Add callbacks to source
var that = this;
for (var i = this.config._events.length - 1; i >= 0; i--) {
var name = this.config._events[i];
console.log(name); // correct
$(this.config.source).on(name, function() {
console.log(name); // value1
console.log(that.config._events[i]); // undefined
});
}
I can’t see what is wrong here. I removed all the complicated versions and put in the simplest, it just doesn’t want to work at all. The first console.log correctly outputs all the correct names, but it acts like the loop happens all at once, then does it again for the inner console.log‘s.
Can anyone see what’s wrong?
In that block
console.log(that.config._events[i]); // undefinediwould end up being -1 every time your closure is called.You would have to do something of the sort in order to create a closure around
i