简体   繁体   English

递归函数调用聚合物

[英]Recursive Function Call Polymer

I'm writing an element that recursively builds a menu tree from a JSON object. 我正在写一个从JSON对象递归构建菜单树的元素。 However, when the function calls itself I get the error: this.buildMenu is not a function 但是,当函数调用自身时,出现错误: this.buildMenu is not a function

Here's buildMenu 这是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 调用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. 递归调用中调用的elem.SubBranch参数是一个数组,并且在此情况下完全有效。

The problem is that inside the forEach callback function, this refers to the context of the callback function itself. 问题是在forEach回调函数内部, 是指回调函数本身的上下文。 Then, when this.buildMenu is called, it fails because the function is not defined within that context. 然后,当调用this.buildMenu时,它将失败,因为该函数未在该上下文中定义。

The forEach function accepts an argument to provide the object you want to be used when the this keyword is used. 当使用this关键字时,forEach函数接受一个参数来提供要使用的对象。 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. 请注意回调后提供的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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