knockout.jsknockout-mapping-plugin

Knockout update only part of the viewmodel


lets assume a viewmode fromJS

var js = { 
            Foo1 : {
                BarA : 'text',
                BarB : 'other text' },
            Foo2 : {
                BarC : 'some text' }}; 

 var vm = ko.mapping.fromJS(js);
  ko.applyBindings(vm);

Now I can do

vm.Foo1.BarB('hello world');

I can also do somthing like

var js = { 
            Foo1 : {
                BarA : 'text',
                BarB : 'hello world' },
            Foo2 : {
                BarC : 'some text' }}; 

 ko.mapping.fromJS(js, vm);

Both scenarios update any field bound to vm.Foo1.BarB

What I would like to do is something like

var foo = {
               BarA : 'text',
               BarB : 'hello world' }; 

     ko.mapping.fromJS(foo, vm.Foo1);

This does not work, I also tried

vm.Foo1(ko.mapping.fromJS(foo));
//and
vm.Foo1 = ko.mapping.fromJS(foo);

None of them are working.

I need this because in my real scenario my model is return from a webservice, the updates Foo1 and Foo2 are also returned and I don't want too much custom mapping.


Solution

  • Apparently there is some mystery additional parameter..

    ko.mapping.fromJS(foo, {}, vm.Foo1);
    

    I have no idea what the second parameter does, but if you use it it works just fine.

    https://stackoverflow.com/a/29598785/2968001