简体   繁体   中英

Recursive Function Call Polymer

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: this.buildMenu is not a function

Here's 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;
}

The original method that calls buildMenu

handleRes: function() {
    this.response = this.$.categoryList.lastResponse;
    this.menuItems = this.buildMenu(this.response);
    //...
}

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 elem.SubBranch argument that is called in the recursive call is an array, and completely valid, if that matters.

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:

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
    }
}, this);

return node;
}

Note the this parameter provided after the callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM