1
function createTextFields(obj) {    
    for (var i = 0; i < obj.length; i++) {
        dataDump = {};    
        for (var key in obj[i]) {
            dataDump[key] = textField.value;
            var callback = function (vbKey) {
                    return function (e) {
                        dataDump[vbKey] = e.source.value;
                    };
            }(key); 
        }
    }
    globalData.push(dataDump);
}

I create textFields on click of button, each time a new one is created from the object. When i change the First or Second or Third TextFields and click on update... the value get's updated on the fourth or the last TextFields TextField's Object...

The callback is called on change of the TextFields

pimvdb
  • 151,816
  • 78
  • 307
  • 352
John Cooper
  • 7,343
  • 31
  • 80
  • 100

2 Answers2

1

It's hard to tell without context, but assuming that different instances of callback are called on change of set text fields, then the problem with closure context of callback.

Callback function holds reference on global dataDump object which is re-assigned on each cycle of the iteration. So, at the end of the for loop all callbacks would reference only one (latest) dataDump object.

Try to add "var" to assignment line.

    var dataDump = {};    
Valera Kolupaev
  • 2,285
  • 14
  • 14
1

You are using window.dataDump in this bit of code, so all your callback functions and such are using this same global variable.

Try var dataDump = {}; instead. You'll probably also want to move your globalData.push(dataDump); inside the loop.

Anomie
  • 92,546
  • 13
  • 126
  • 145