克隆JS TreeModel树 [英] Cloning a JS TreeModel tree

查看:311
本文介绍了克隆JS TreeModel树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要克隆使用 TreeModel.js 制作的树. 我真正需要做的是复制它,对其进行更改,然后检查节点数是否减少.如果是这样,请还原为原始树.这是到目前为止我要复制它的一个小例子,这是不正确的:

I need to clone a tree I made using TreeModel.js. What I exactly need to do is duplicating it, make changes to it and check if the number of nodes decreased. If it did, revert to the original tree. Here's a small example of what I do so far to duplicate it, which is not correct:

var tree = new TreeModel();
var root = tree.parse({
    id: 0,
    name: "Root",
    children: [{id: 1, name: "1", children: []},{id: 2, name: "2", children: []}]
});

console.log(root)
var dup = tree.parse(root)
console.log(dup)

这是小提琴.通过查看控制台,您将看到树木之间的区别:

Here's a Fiddle. You'll see the difference between the trees by looking at the console:

Node {config: Object, model: Object, children: Array[2], isRoot: function, hasChildren: function…}
Node {config: Object, model: Node, children: Array[2], isRoot: function, hasChildren: function…}

有什么方法可以正确克隆这样的结构吗?我一直在寻找克隆JS对象的方法,但仍然找不到完全克隆该对象的方法(例如模型之类的属性的原型...)

Is there any way to properly clone such a structure? I looked for cloning JS object but still, I can't find a way for cloning this object exactly (such as the prototypes of properties like the model...)

推荐答案

您可以深度克隆第一棵树的模型,然后再次对其进行解析以获得第二棵树.

You can deep clone the model of the first tree and parse it again to get a second tree.

以您的示例为例:

function deepCopy(obj) {
    // You can also use the jquery extend method here
    return JSON.parse(JSON.stringify(obj));
}

var dup = tree.parse(deepCopy(root.model));

重要提示:如果不深度克隆模型,而是再次对其进行解析,则最终将得到两棵树共享的相同基础模型,这肯定会导致不一致.

Important: If you do not deep clone the model, and just parse it again, you'll end up with the same underlying model shared by both trees which will certainly cause inconsistencies.

这篇关于克隆JS TreeModel树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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