当为视图模型使用 KO 映射插件,然后绑定到选择时,未设置该值。
jsFiddle:
http://jsfiddle.net/JerryClinesmith/pCn9E/
HTML:
<h1>With ko.mapping (manager not set)</h1>
<div id="option-mapping">
<select data-bind="options: availManagers, value: manager, optionsText: 'name', optionsCaption: 'Pick one'"></select>
<div data-bind="text: json"></div>
</div>
<h1>Without ko.mapping (manager is set)</h1>
<div id="option-no-mapping">
<select data-bind="options: availManagers, value: manager, optionsText: 'name', optionsCaption: 'Pick one'"></select>
<div data-bind="text: json"></div>
</div>
JavaScript:
var origData = {
manager: {},
availManagers: [
{id: 1, name: 'Tom'},
{id: 2, name: 'Joe'},
{id: 3, name: 'James'}]
};
var ViewModel = function(data) {
var self = this;
ko.mapping.fromJS(data, {}, self);
self.json = ko.computed(function() {
return ko.toJSON(ko.mapping.toJS(self));
});
};
var ViewModelNoMapping = function(data) {
var self = this;
self.manager = ko.observable(data.manager);
self.availManagers = ko.observableArray(data.availManagers);
self.json = ko.computed(function() {
var obj = ko.toJS(self);
delete obj.json;
return ko.toJSON(obj);
});
};
var vm = new ViewModel(origData);
var vm2 = new ViewModelNoMapping(origData);
ko.applyBindings(vm, document.getElementById('option-mapping'));
ko.applyBindings(vm2, document.getElementById('option-no-mapping'));
没有映射插件的视图模型似乎可以按预期工作。