JSFiddle - React, Tailwind, and code Playground
by alnitak
HTML
<div>
<input id="button1" type="button" value="Create Object Tree" onclick="button1Click();" /><br />
<input id="button2" type="button" value="Retrieve and Execute" onclick="button2Click();" /><br />
</div>
JavaScript
button1Click = function() {
var child = new MyChild();
child.data.id = 1;
var c2 = new MyChild();
c2.data.id = 2;
var p = new MyParent();
p.data.id = "A";
p.data.children.push(child);
p.data.children.push(c2);
p.save("A");
}
button2Click = function() {
var storedParent = new MyParent();
storedParent.load("A");
storedParent.test(); // This works
alert(storedParent.data.children.length); // This displays "1" like I would expect
alert(storedParent.data.children[0].data.id); // This does NOT work.
storedParent.data.children[0].test(); // This does NOT work.
}
function MyChild() {
this.init();
}
MyChild.prototype = {
init: function() {
this.data = {
id: 0,
fullName: ""
};
},
save: function(key) {
},
load: function(key) {
},
test: function() {
alert("Testing Child functions");
}
}
function MyParent() {
this.init();
}
MyParent.prototype = {
init: function() {
this.data = {
id: "",
children: []
}
},
save: function(key) {
window.localStorage.setItem(key, JSON.stringify(this.data));
},
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 < children.length; ++i) {
children[i] = $.extend(new MyChild(), children[i]);
}
}
},
test: function() {
alert("Testing Parent functions");
}
}