Convert ko.toJSON back to an observable array

I have the following observable array:

self.users = ko.observableArray(); 

which has elements of the following object:

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

I need to save this observable array locally on the user machine (simplified example), so for this I use the localstorage and ko.toJSON . This works fine, and all data is stored in localstorage, including the score element, which is observable. The problem is that I cannot convert this string back to an observable array. When I do JSON.parse and pass it to a self.users score , it is no longer observed. Is there any function like ko.parse to ko.toJSON back ko.toJSON ?

+4
source share
1 answer

It is actually quite simple. However, you originally built the self.users collection in the same way you created it with 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.

+4
source

Source: https://habr.com/ru/post/1493824/


All Articles