Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You need to store your <code>data</code> within each object, not within its <code>prototype</code>.</p> <p>Data stored in in the <code>prototype</code> of an object is shared between all instances and won't be serialised by <code>JSON.stringify</code>, so your object data never ends up in the local storage.</p> <p>To fix, add data to <code>this</code> within the <code>this.init()</code> function:</p> <pre><code>MyChild.prototype = { init: function() { this.data = { id: 0, fullName: "" }; }, ... } MyParent.prototype = { init: function() { this.data = { id: "", children: [] } }, ... } </code></pre> <p>Working sample at <a href="http://jsfiddle.net/alnitak/fdwVB/" rel="nofollow">http://jsfiddle.net/alnitak/fdwVB/</a></p> <p>Note that attaching the functions in <code>MyChild</code> to the retrieved data is tricky. The code below appears to work:</p> <pre><code>load: function(key) { var temp = window.localStorage.getItem(key); if (temp != null) { this.data = JSON.parse(temp); var children = this.data.children; for (var i = 0; i &lt; children.length; ++i) { children[i] = $.extend(new MyChild(), children[i]); } } }, </code></pre> <p>But note that it works by constructing a new "default" child for each retrieved entry, and then overwriting that child's data with the serialised values.</p> <p>This could be problematic if the constructor has "side effects".</p> <p>A better approach might be to allow the <code>MyChild()</code> constructor to take an optional complete object of initial values to use instead of the default values.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload