Search code examples
javascriptjsonknockout.jsknockout-mapping-plugin

Knockout Mapping: JSON grows when mapping and saving multiple times


When I take a knockout object and serialize it to JSON by doing ko.toJSON, and then unserialize it from JSON using ko.mapping.fromJSON multiple times, the loaded object has this __ko_mapping__ property that recursively grows.

Sample code:

var joe = new Person();
for (var i = 0; i < 10; i++) {
    var json = ko.toJSON(joe);
    joe = ko.mapping.fromJSON(json);
}

Simple JSFiddle that reproduces it:

http://jsfiddle.net/Gc89Q/1/

How can I load and save multiple times without having the serialized json form grow to be gigantic?

I was considering just setting the __ko_mapping__ property to undefined when loading, but am wondering if there is a better way or something I am missing.

Is this a bug I file an issue for?


Solution

  • Don't overwrite the model. Instead, pass it to fromJSON so the model is updated:

    ko.mapping.fromJSON(json, joe);
    

    http://jsfiddle.net/Gc89Q/2/