Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript recursive function reference this
    primarykey
    data
    text
    <p>I'm trying to create a function that will generate a tree like structure such that each item contains a reference to it's parent item. </p> <p>I have a function that calls itself when creating the children but am having a tough time with it, it seems that once it is called from within itself <code>this</code> still refers to the top level item rather than the current one. </p> <p>Logging to console what the item is I can see that parent always refers to the first item in the chain (or is absent) when deeper than the first level. It creates the tree, but references to parent are lost for items besides the first.</p> <pre><code>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, {}); </code></pre> <p>Having a bit of trouble getting a fiddle going, but here is some sample data:</p> <pre><code>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"}]}'); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload