When using the KO mapping plugin for a view model, then binding to a select, the value is not set.
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'));
A view model without the mapping plugin seems to work as expected.
I’ve hit the same problem before with a blank object, it doesn’t seem to create an observable….which means manager is a plain object, which means computed never triggers.
eg, change it to… (note: I changed manager: {} to manager: ” which then gives it something to convert to an observable. Which then makes things tick along ok… also changed the convert to json function, as the other one didn’t seem to show the the values on manager.
I’m not sure if this is a bug in the mapping plugin, both with not converting to a observable, and also not converting to the correct json for display.
and just to confirm, I downloaded the mapping plugin and wrote the test :-
with the result