0

I'm trying to de-reference a property on a JavaScript object, but am not getting the expected result.

I have an array of Knockout view-models (I don't think the problem is Knockout-specific), each of which has an observable, Selected. I add a subscription to this observable so that a function, crossSelectTargetLangs is called when the value of Selected is changed.

Furthermore, I add this subscription inside a for... loop.

var tl = 0,
    tlMax = allLangVMs.length,
    vmLang,
    selectedCode;

// for each 'vmLang' view-model in the 'allLangVMs' array...
for (; tl < tlMax; tl++) {

    // local variable for the context view-model    
    vmLang = allLangVMs[tl];

    // add the subscription to this observable    
    vmLang.Selected.subscribe(function() {

        // de-reference the vmLang.Code property
        selectedCode = (function(code) {
            return code;
        }(vmLang.Code));

        // pass the de-ref'd value to the target function    
        crossSelectTargetLangs(selectedCode);
    });
}

However, regardless of which view-model had its Selected observable updated, the argument passed to the target function is always the Code from the last element in the array, i.e. it doesn't appear to be de-referencing.

What am I doing wrong?

awj
  • 7,482
  • 10
  • 66
  • 120

1 Answers1

0

The problem is that you are making dereferencing in a wrong place. The code should look like this:

var tl = 0,
    tlMax = allLangVMs.length,
    vmLang,
    selectedCode;

// for each 'vmLang' view-model in the 'allLangVMs' array...
for (; tl < tlMax; tl++) {

    // local variable for the context view-model    
    vmLang = allLangVMs[tl];

    (function(vmLangParam) {   
      vmLangParam.Selected.subscribe(function() {   
          crossSelectTargetLangs(vmLangParam.Code);
      });
    })(vmLang);
    
}
lunochkin
  • 684
  • 4
  • 17