I’m new to the mapping plugin and think that I’m missing something obvious.
How can I get ko.mapping to ‘deeply’ create members of observable arrays as observables themselves? I’ve looked at ‘create callbacks’ and ‘options’ in the documentation, but don’t see anything obvious.
I have quite a large object model and so would prefer not to have to bind the viewModel by hand. Also, as a side issue perhaps, there is a need to add elements dynamically as observables as well.
html
<p>
here, ko.mapping succesfully creates an observable...<br/>
<input data-bind="value:someText, valueUpdate:'afterkeydown'"></input>
</p>
<p>
however, here, the contents of the observable array are not observables...</br>
<span data-bind="foreach: { data: years, as: 'year' }">
<input data-bind="value:year, valueUpdate:'afterkeydown'"></input>
<br />
</span>
<button data-bind="click:function(){addYear();}">add</button>
</p>
<p><br /><br /><div data-bind="text: ko.toJSON($root)"></div></p>
javascript
var model={
someText: 'Hello',
years:[2000,2001,2002]
};
var viewModel = ko.mapping.fromJS(model);
viewModel.addYear=function(){viewModel.years.push(ko.observable(""));}
ko.applyBindings(viewModel);
Here’s a jsFiddle link
Thanks very much for your help,
DS
I had to change your array to be an array of properties instead of just numbers. If you have just an array numbers, the mapping plugin doesn’t covert them to observables.
See the Updated Fiddle