如何使用循环引用保存对象? [英] How to save an object with circular references?

查看:121
本文介绍了如何使用循环引用保存对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在本地保存一个具有循环引用的对象。我有什么选择?



我的第一个想法是使用HTML5本地存储,但由于循环引用,我无法对此对象进行字符串化。



具体来说,我正在尝试保存当前选择的DOMSelection对象。



示例:

  var sel = window.getSelection(); 
var selstring = JSON.stringify(sel); //在这里休息...
localStorage.setItem(selection,selstring);

我现在能让stringify工作的唯一方法就是忽略某些对象:

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

返回v;
});

但这给我留下了一个相当空的DOMSelection对象,这对我所需要的还不够。 / p>

我还有其他方法可以保存这个对象吗?唯一的要求是它在移动游猎中运行,其他任何东西都是真的。解决方案可以是javascript或jquery(或任何其他js lib,如果需要)。



感谢您提供的任何帮助。

解决方案

查看 Crockford的JSON-JS GitHub回购。它有一个文件 cycle.js ,它可以转换为使用JSON循环引用的对象并使用JSONPath返回。请参阅回购中的最后一段读我和文件的评论。


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.

解决方案

Check out Crockford's JSON-JS GitHub repo. It has a file, cycle.js, which can supposedly convert objects with circular references to JSON and back using JSONPath. See the last paragraph in the repo's read me and the file's comments.

这篇关于如何使用循环引用保存对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆