localStorage['key'] = 'value';Result was great, and I got nice alert with 'value' on it.
alert(localStorage['key']);
Quite excited, i created functionality i wanted to have, created nice tests and found out that something is not great at all and after localizing error I have found out that similar piece of code is not working as good as previous.
localStorage['key'] = {test:'value'};
alert(localStorage['key'].test);
In this case, alert returned 'undefined', but not 'value', what was quite unexpected.
However this code
localStorage['key'] = {test:'value'};says that I have nice '[object Object]'. I checked it a bit and had found that this script
alert(localStorage['key']);
localStorage['key'] = {test:'value'};says that my localStorage result is in fact 'string', which was quite unexpected, as it should be Object.
alert(typeof localStorage['key']);
As it turned out, localStorage uses structured clone algorithm and whether because of this or for some other reason it converts my object into string, stores it as such and therefore looses all properties and values.
Finally, I have found easy way to solve this problem by converting my object into JSON string. Fortunately Firefox have native JSON coverter functions and everything can be done simply like
localStorage['key'] = JSON.stringify({test:'value'});In WRT there is no such nice lib, but it is possible to download it at json.org. And it can be nicely used like this:
alert(JSON.parse(localStorage['key']).test);
widget.setPreferenceForKey(JSON.stringify({test:'value'}), 'key');There is small issue though. As you see JSON lib is used to convert object to string, but it was not able to convert string to object on my Nokia device. But this small eval hack still works great and I am getting my value as expected.
alert(eval(widget.preferenceForKey('key')).test);
No comments:
Post a Comment