Question

I have this code:

this.mGroupFunctions={};
        for(var i=0; i<cols.length; i++){
            var col=cols[i];
            this.mGroupFunctions[col]=function(oContext) {
                var name = oContext.getProperty(col);
                return {
                  key: name,
                  text: name
                };
              };
        }

If I debug it i obtain enter image description here

where into a function I insert col and not the value of variable col!!!

How can I resolve my problem??

Was it helpful?

Solution

When the function runs, the variable col no longer contains the value that it had when the function was created. You can use an immediately invoked function expression (IIFE) to create a closure that captures the value of col for each iteration in the loop:

this.mGroupFunctions = {};
for(var i=0; i<cols.length; i++){      

  this.mGroupFunctions[cols[i]] = (function(col){

    return function(oContext) {
      var name = oContext.getProperty(col);
      return {
        key: name,
        text: name
      };
    };

  })(cols[i]);

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top