1

我在 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?

4

1 回答 1

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);
}
于 2013-01-14T21:07:32.760 回答