0
我试图在JavaScript对象上取消引用属性,但没有获得预期的结果。从数组内部取消引用JavaScript属性
我有一个Knockout视图模型数组(我认为问题不是Knockout特定的),每个模型都有一个可观察的Selected
。我添加了对此可观察值的订阅,以便在Selected
的值更改时调用函数crossSelectTargetLangs
。
此外,我在for...
循环内添加此订阅。
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);
});
}
然而,无论哪个角度的模型有其Selected
可观察到的更新,传递到目标函数的参数总是Code
从阵列中的最后一个元素,即它不会出现是取消引用。
我在做什么错?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures#Creating_closures_in_loops_A_common_mistake –