Recursive Function Call Polymer

时间:2016-02-12 21:07:45

标签: javascript polymer polymer-1.0

I'm writing an element that recursively builds a menu tree from a JSON object. However, when the function calls itself I get the error: var nmech = data.nmech; var nelect = data.nelect;

Here's buildMenu

this.buildMenu is not a function

The original method that calls buildMenu

buildMenu: function(items) {
var node = new Array();

items.forEach(function(elem,index,arr) {
    node.push(elem.Name);

    if (elem.SubBranch.length > 0) {
        return this.buildMenu(elem.SubBranch); //error is here
    }
});

return node;
}

I've verified that data is there and formatted correctly. If I comment out the recursive call, I get the first layer of results. So, it's working in that respect.

The handleRes: function() { this.response = this.$.categoryList.lastResponse; this.menuItems = this.buildMenu(this.response); //... } argument that is called in the recursive call is an array, and completely valid, if that matters.

1 个答案:

答案 0 :(得分:7)

The problem is that inside the forEach callback function, this refers to the context of the callback function itself. Then, when this.buildMenu is called, it fails because the function is not defined within that context.

The forEach function accepts an argument to provide the object you want to be used when the this keyword is used. In this case you may use the following code:

 <servlet-mapping>
 <servlet-name>default</servlet-name>
 <url-pattern>*.css</url-pattern>
 </servlet-mapping>

Note the this parameter provided after the callback.