SteveSanderson/knockout.mapping — Issue #41: Updating or inserting an item in an observable array
Author: luv2code
Created: 2011-12-09 16:28:57+00:00
State: open

this situation is that objects are pumped from a service one at a time and stored in an array. Also, updates to those objects are received one at a time. When there is a key defined for the mappedObservableArray, it would be nice if fromJS inserted or updated based on key match.

for instance:
var vm =ko.mapping.fromJS( [ ko.mapping.formJS({name:'matt', age:20}) ], {
key:function(data) {
return ko.utils.unwrapObservable(data.name);
}
});

ko.mapping.fromJS(ko.mapping.fromJS({ name: 'jim', age: 23 }), vm); //should insdert jim into the array

ko.mapping.fromJS(ko.mapping.fromJS({ name: 'matt', age: 23 }), vm); //should change matt's age to 23

I use this pattern quite a lot.
currently, I'm doing this:
var index = vm.mappedIndexof(data);
if(index < 0) {
vm.push(ko.maping.fromJS(data));
} else {
ko.mapping.fromJS(data, vm()[index]);
}