King Julien
King Julien

Reputation: 11338

Convert ko.toJSON back to observable array

I have the following observable array:

self.users = ko.observableArray();

which has an items of the following object:

function user(id, name, score) {
    this.id = id;
    this.name = name;
    this.score = ko.observable(score);
}

I need to store this observable array locally in user's computer (simplified example) so I use localstorage and ko.toJSON function for this. This works fine and all the data is stored in localstorage, including the score item, which is an observable itself. The problem is that I can't convert this string back to observable array. When I do JSON.parse and pass it to self.users score isn't observable any more. Is there any function like ko.parse to revert back ko.toJSON?

Upvotes: 4

Views: 3260

Answers (1)

Kyeotic
Kyeotic

Reputation: 19857

This is actually pretty straightforward. However you initially constructed the self.users collection is the same way you will construct it with the JSON data. This is one example:

function User(data) {
    this.id = data.id;
    this.name = data.name;
    this.score = ko.observable(data.score);
}

...
//inside viewmodel
var storage;
self.store = function() {
    storage = ko.toJSON(self.users());
    self.users.removeAll();
};
self.load = function() {
    var parsedUsers = JSON.parse(storage);
    self.users(ko.utils.arrayMap(parsedUsers, function(u) {
        return new User(u);
    }));
};

Here is a working fiddle using this method.

Upvotes: 4

Related Questions