Question

Have a look at this small example.

<select data-bind="options: Days, optionsText: 'title'"></select>
<input type="button" value="update" data-bind="click: update" />

<script type="text/javascript">
var Days = {'Days': [{"id":1,"title":"Monday"},{"id":2,"title":"Tuesday"},{"id":3,"title":"Wensday"}]};

var DaysUpdate = {'Days': [{"id":3,"title":"Wednesday"},{"id":4,"title":"Thursday"},{"id":5,"title":"Friday"}]};

var mapping = {    
    'Days': {        
        key: function(data) {            
            return ko.utils.unwrapObservable(data.id);        
        }    
}}

var viewModel = {
    Days: ko.observableArray(),
    update: function() {
        ko.mapping.fromJS(DaysUpdate, mapping, viewModel);
    }
}

ko.mapping.fromJS(Days, mapping, viewModel);


ko.applyBindings(viewModel);

</script>

In this example data is mapped partially. First from Days object, then (by clicking update button) from DaysUpdate object. The the second update removes "Monday" and "Tuesday" objects from the array. How do I make those stay?

PS. Thanks to Mark Robinson for better structured example.

Was it helpful?

Solution

This is a common question re the mapping plugin. Currently there is no way to do this with the plugin itself. It's been a bugging me for a while. The plugin assumes that the array you gave it is the new contents of the array so removes the other items.

The only solution I know of at present is to loop through the collection and manually map each element.

http://jsfiddle.net/madcapnmckay/5878E/

One of these days I'll get around to trying to come up with a proper solution and send a pull request to the mapping plugin guys.

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top