Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

javascript - How to save an object with circular references?

I want to save locally an object which has circular references. What are my options?

My first thought was using HTML5 local storage but I can't stringify this object due to the circular references.

Specifically I'm trying to save the DOMSelection object of the current selection.

Example:

  var sel = window.getSelection();
  var selstring = JSON.stringify(sel); // Breaks here ...
  localStorage.setItem("selection",selstring);

The only way I could get the stringify to work now is by ignoring certain objects like so:

var selstring = JSON.stringify(sel,function(k,v){
    if( k=="anchorNode" ||
        k=="baseNode" ||
        k=="extentNode" ||
        k=="focusNode") return undefined;

    return v;
});

But this leaves me with a rather empty DOMSelection object which isn't enough for what I need.

Is there any other way I can save this object? The only requirement is that it runs in mobile safari, anything else goes really. The solution can be either in javascript or jquery (or any other js lib if need be).

Thanks for any help you can provide.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The answer here lies in understanding what data you really need to store persistently and minimizing that to only what is needed and then adding a method or function to get just that information and then saving that. I don't know your application but for a text selection, you would probably just need a persistent indication of which object it was and the start and end points of the text selection.

Then, on the restore side, you would build a function to build a selection using the data you store. It's not as simple a serialize/deserialize, but it will work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...