Knockout:多项选择,对象无效

时间:2014-09-21 13:53:13

标签: javascript knockout.js

我正在使用Knockout 3.2并且我正在尝试显示带有一些选定值的多选下拉列表,但未选择这些值。问题是KO没有填充选项的'value'属性:

<select data-bind="options: availableCountries, selectedOptions: chosenCountries, optionsText: 'name'" size="5" multiple="true">
    <option value="">France</option>
    <option value="">Germany</option>
    <option value="">Spain</option>
</select>

VM:

var viewModel = {
      availableCountries : ko.observableArray([{name:'France'}, {name:'Germany'}, {name:'Spain'}]),
        chosenCountries : ko.observableArray(['Germany'])
    };

如果我将availableCountries变成一个简单的字符串数组而不是对象,那么它就可以了。

You can see a live sample here

1 个答案:

答案 0 :(得分:2)

var viewModel = {
    availableCountries : ko.observableArray([{name:'France'}, {name:'Germany'}, {name:'Spain'}]),
    chosenCountries : ko.observableArray(['Germany'])
};

['Germany']不是{name: 'Germany'}

如果你这样写chosenCountries : ko.observableArray([{name: 'Germany'}]),这会导致两个不同的对象,具有相同的属性name和值'Germany'

var viewModel = (function() {
   var self = {};
   self.availableCountries = ko.observableArray([{name:'France'}, {name:'Germany'}, {name:'Spain'}]);
   self.chosenCountries = ko.observableArray([self.availableCountries()[1]]);
   return self;
})();
ko.applyBindings(viewModel);

我将viewModel更改为一个名为function的instand,它返回viewModel。

(function(){...})() &lt; -call

http://jsbin.com/monasijufaya/1/edit?html,js,output