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 –