knockout selectedOption计算不起作用

时间:2018-04-09 19:10:19

标签: javascript knockout.js

我遇到了一个对我没有任何意义的奇怪问题。

下面的代码会正确显示下拉列表,但selectedOptions不适合阅读。读取函数会被调用,但默认值3不会被设置。

写功能肯定有效。

如果我使用fChosenAnswer,则默认正确设置#3被预先选择。

HTML:

 <!-- this one doesn't have a default but it should be defaulting to 3 -->
<select class="example" data-bind="options: AvailableAnswersArray, selectedOptions: ChosenAnswer"></select>

<!-- this one does correctly default to 3 -->
<select class="example2" data-bind="options: AvailableAnswersArray, selectedOptions: fChosenAnswer"></select>
在viewmodel中:

this.fChosenAnswer = ko.observableArray([3]);

this.ChosenAnswer = ko.computed({
    read: function () {
        console.log("ChosenAnswer read function is hit but the drop down doesn't show it as selected."); //this log shows in the console
        return ko.observableArray([3]);
    },
    write: function (value) {
        console.log("updated chosen answer to ", value);
        // this log shows in the console
    },
    owner: this
});

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

感谢Adrian,答案是返回[3]而不是observableArray。

read: function () {
    return [3];
},