简体   繁体   English

带回调的Javascript对象方法中的递归

[英]Recursion in Javascript object method with callback

I have a challenge with recursion within a javascript object method that I am hoping someone can help with. 我有一个javascript对象方法中的递归挑战,我希望有人可以提供帮助。 It may require some re-factoring of my code. 它可能需要对我的代码进行一些重新分解。

I am creating a number of objects of the same type using an object factory - To keep things simple, let's assume the object has following properties; 我正在使用对象工厂创建许多相同类型的对象 - 为了简单起见,我们假设对象具有以下属性;

this.objID;
this.dependents      = []; //array of objects linked to this one
this.otherProperty   = "";
this.anotherProperty = "";

Now consider the following code: 现在考虑以下代码:

MyObject.prototype.updateDependents = function() {
    doStuff(this);
    this.getDependents(doStuff);
};


MyObject.prototype.getDependents = function(callback,callback_opts) {
    var deps = [];
    if (typeOf callback !== "function") { callback = false; }
    for (var i = 0; i < this.dependents.length; i++) {
        deps.push(this.dependents[i]);
        if (callback) {
            callback(this.dependents[i],callback_opts);
        }
    }
    return deps;
};

function doStuff(myObj) {
    //..do some stuff to "myObj" (i.e. update other properties)
};

I am calling the method 'updateDependents' on an object and then want to get all the other objects that are dependents of that object (as stored in the 'dependents' property) and apply the function 'doStuff' to those dependent objects. 我在一个对象上调用方法'updateDependents',然后想要获取该对象的所有其他对象(存储在'dependents'属性中)并将函数'doStuff'应用于那些依赖对象。 This bit works fine. 这个位工作正常。

The bit I am struggling with is how to then call the getDependents method recursively on the objects that are dependents of the first object and apply the same callback function, and then do the same on any further levels of dependent objects, etc (ie multiple, and unknown levels of dependency). 我正在努力的一点是如何在第一个对象的依赖对象上递归调用getDependents方法并应用相同的回调函数,然后在依赖对象的任何其他级别上执行相同的操作(即多个,和未知的依赖程度)。

Any suggestions on the best way to do this??? 有关最佳方法的任何建议???

You would simply call it on each of the dependents you are traversing: 您只需在您正在遍历的每个家属上调用它:

for (var i = 0; i < this.dependents.length; i++) {
    deps.push(this.dependents[i]);
    deps.push.apply(deps, this.dependents[i].getDependents(callback,callback_opts));
    …

The order in which you call this (vs. when you push the single dependent and call the callback on it) determines the traversal order . 您调用此命令的顺序(相对于推送单个依赖项并在其上调用回调时)确定遍历顺序 Use what you need or like. 使用你需要或喜欢的东西。

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

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