2013-12-12 67 views
6

我想创建一个函数,它将生成一个像结构这样的树,以便每个项目包含对它的父项目的引用。Javascript递归函数参考这个

我有一个函数可以在创建孩子时调用自己,但是对它有困难的时候,似乎一旦从它自己内部调用它,this仍然指向顶级项目而不是当前项目。

记录控制项目是什么我可以看到,父母始终指的是链中的第一项(或缺席)比第一级更深。它创建树,但除了第一个项目之外,对父项的引用会丢失。

var Item = function (item, parent) { 
    console.log('item is :' + item.name); 
    this.parent = parent; 
    console.log('parent is: ' + parent); 
    var fields = _.union(_.keys(item), _.keys(this.parent)); 
    _.each(_.without(fields, ['parent','children']), function (prop) { 
    this[prop] = angular.isDefined(item[prop]) ? item[prop] : this.parent[prop]; 
    }, this); 

    this.children = []; 
    if (item.children) { 
    this.children = _.map(item.children, function (child) { 
     console.log('this is : ' + this); 
     return new Item(child, this) 
    }, this); 
    } 
}; 

var tree = new Item(root, {}); 

有一点麻烦小提琴去,但这里是一些样本数据:

var root = JSON.parse('{"id":"1","name":"root item","root":"1","lft":"1","rgt":"22","level":"1","type": 
"category","parent_id":"1","deadline":null, 
"children":[ 
{"id":"2","name":"item 1","root":"1","lft":"14","rgt":"15","level":"2","type":"category","parent_id":"1"}, 
{"id":"6","name":"item 2","root":"1","lft":"16","rgt":"19","level":"2","type":"category","parent_id":"1"}, 
{"id":"10","name":"item 3","root":"1","lft":"20","rgt":"21","level":"2","type":"item","parent_id":"1"}]}'); 
+0

只是一个错字,我一直在试验,并忘记修改之前发布。修正它在这里,问题仍然是一样的。 – JPR

+1

你可以用一些虚拟数据为此创建小提琴吗? –

+0

当然,可能需要几分钟才能把它放在一起。谢谢。 – JPR

回答

1

的问题是在你的_.without method的使用。要排除的元素作为可变数量的参数传递,而不是数组。

错误用法:

_.without(['a','b'],['a']) 

结果['a', 'b'](不是你想要的)

鉴于:

_.without(['a','b'],'a') 

得到您预期的结果:['b']

这里是一个updated fiddle与修复。

注意:为避免循环引用,我在“结果”输出中输出parent.id而不是parent

1

它的工作对我来说。我简化了代码并添加了孙子项目。看看: http://jsfiddle.net/7QYQL/1/

var grandchild = {}; 
grandchild.name = 'grandchild'; 
var child = {}; 
child.name = 'child'; 
child.children = []; 
child.children[0] = grandchild; 
var root = {}; 
root.name = 'root'; 
root.children = []; 
root.children[0] = child; 

的问题已得到解决_.without(),它接受一个列表而不是一个数组作为第二个参数。

_.without(fields, 'parent','children') 

这一个工程: http://jsfiddle.net/eRbhm/13/

+0

感谢和大拇指为此。我试了你的第一个答案,它的工作,但我的代码仍然没有,我不明白你是如何从根本上不同于我在做什么。修复_.没有立即修复它,我完全忽略了它。 – JPR