简体   繁体   English

如何使用循环引用保存对象?

[英]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. 我的第一个想法是使用HTML5本地存储,但是由于循环引用,我无法对该对象进行字符串化。

Specifically I'm trying to save the DOMSelection object of the current selection. 具体来说,我正在尝试保存当前选择的DOMSelection对象。

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. 但这给我留下了一个相当空的DOMSelection对象,不足以满足我的需要。

Is there any other way I can save this object? 还有其他方法可以保存该对象吗? The only requirement is that it runs in mobile safari, anything else goes really. 唯一的要求是它可以在移动safari中运行,其他任何事情都是真的。 The solution can be either in javascript or jquery (or any other js lib if need be). 该解决方案可以使用javascript或jquery(如果需要,也可以使用其他js库)。

Thanks for any help you can provide. 感谢您的任何帮助,您可以提供。

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. 它不是简单的序列化/反序列化,但是可以工作。

Check out Crockford's JSON-JS GitHub repo . 查看Crockford的JSON-JS GitHub存储库 It has a file, cycle.js , which can supposedly convert objects with circular references to JSON and back using JSONPath. 它有一个文件cycle.js ,它可以将具有循环引用的对象转换为JSON并使用JSONPath转换回来。 See the last paragraph in the repo's read me and the file's comments. 请参阅回购的“阅读我”和文件注释中的最后一段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM