Search code examples
javascriptknockout.jsknockout-mapping-plugin

Specify object type after using ko.mapping.fromJS


im trying to clone a Knockout VM. I found some examples doing it by:

var oldType = new myVM();
var newType = ko.mapping.fromJS(ko.toJS(oldType));

It works fine but newType is now an object and not myVM type as i wanted. is there a way to specify newType as myVM?

Thanks.


Solution

  • My answer is probably somewhat bias as I don't like the knockout mapping functionality, I think it promotes bad habits.

    If I were doing this I would create a constructor on myVM which accepts an instance of myVM as a parameter and then sets all of the properties in the constructor and I'd write the mapping by hand.

    That said, you can do what you want with knockout mapping:

    var oldType = new myVM();
    var newType = new myVM();
    ko.mapping.fromJS(ko.toJS(oldType), newType);
    

    Edit Just checked the knockout docs to refresh my memory and you may actually need to pass the new type as the third parameter, with an empty options object as the second:

    ko.mapping.fromJS(ko.toJS(oldType), {}, newType);
    

    Although the example page seems to suggest both ways are valid which I doubt.