我在JS中有以下内容:
function reportCriteria(fieldId,fieldName,filterOption,optionText,filterChoice) {
return {
fieldId: fieldId
fieldName: fieldName,
filterOption: filterOption,
optionText: optionText,
filterChoice: filterChoice,
description: ko.computed(function () {
return fieldName + " which " + optionText + " " + filterChoice;
})
};
}
我的模型中有一个observableArray,它包含了我推送的内容:model.criteriaEntries.push(new reportCriteria(paramshere));
所有看起来都没问题,直到我尝试编辑这样的:
var criItem = ko.utils.arrayFirst(model.criteriaEntries(), function (item) {
return item.fieldId == id;
});
if (criItem) {
criItem.filterOption = option;
criItem.optionText = opttext;
criItem.filterChoice = choice;
model.criteriaEntries.valueHasMutated();
}
我没有错误,我可以调试并看到对象已更改,但计算的描述没有更新,因为尽管添加了valueHasMutated,屏幕上没有任何变化?
答案 0 :(得分:4)
你的问题是你通过criItem.optionText = opttext覆盖了optionText;
不要那样做。而是更新optionText:
criItem.optionText(opttext);
然后您的计算将相应更新。
修改 以下是您的报告创建代码应如下所示:
function reportCriteria(fieldId,fieldName,filterOption,optionText,filterChoice) {
var report = {
fieldId: fieldI),
fieldName: fieldName,
filterOption: ko.observable(filterOption),
optionText: ko.observable(optionText),
filterChoice: ko.observable(filterChoice)
};
report.description = ko.computed(function () {
return report.fieldName + " which " + report.optionText() + " " + report.filterChoice();
});
return report;
}
以下是编辑方法:
var criItem = ko.utils.arrayFirst(model.criteriaEntries(), function (item) { return item.fieldId == id; });
if (criItem) {
criItem.filterOption(option);
criItem.optionText(opttext);
criItem.filterChoice(choice);
}