javascript - Pack and unpack complex object architecture with JSON -


i've been looking html 5's new local storage , seems pretty cool far. i've decided use json serialize objects strings , parse them objects, sounds nice. however, it's easier said done. i've discovered can't json.stringify() object , expect pack nicely you, can't figure out have instead.

that's not all, though: object contains 2 arrays, each of holds type of object , 1 of multidimensional. here's rather complex , inter-dependent object architecture looks like:

function vector2(x, y) {     this.x = x;     this.y = y; }  function bar(id, position) {     this.id = id;     this.position = position; }  function goo(state, position) {     this.on = state;     this.position = position; }  function foo(name, size) {     this.name = name;     this.size = size;     this.bars = new array(width)     this.goos = new array(10);      this.initialize(); }  foo.prototype.initialize() {     for(var x = 0;x<this.size.x;x++) {             this.bars[x] = new array(this.size.y);          for(var y=0;y<this.size.y;y++) {             this.bars[x][y] = new bar(x + y, new vector2(x, y));         }     }      for(var = 0;i<this.goos.length;i++) {         this.goos[i] = new goo(on, new vector2(i, i/2 + 1));     } } 

each of objects has plenty of additional functions well, each added using same prototype method used add method foo. said, complex. question is, how serialize this? need tack on tojson() functions every object?

finally, once i've packed , saved localstorage, know how retrieve it, i'm pretty clueless on how unpack json. that's matter time, though, , suspect might bit easier figure out on own once learn how pack up.

note: wouldn't such potentially broad question, couldn't find here on or (admittedly weak) google-fu addresses issue, , don't know how break question down further.

usually, don't serialize complex data structures in javascript because normal serialization doesn't handle multiple difference things have references same object, can't handle circular references, etc...

what recommend instead figure out real state of application is. not whole instantiated object structure, minimum amount of information needed reconstruct state of data. then, once you've figure out (it should data, no actual objects), can create functions or methods data data structures or create new data structure data.

in looking @ code, actual state of foo object 2 dimensional array of bar objects , 1 dimensional array of goo objects , name , size. bar has x, y , id. goo has state , x , y. pretty easy state write foo method generate , foo method accept state saved storage.


Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -