簡體   English   中英

嵌套函數創建層次結構

[英]Nested functions to create hierarchical structure

我試圖用回調創建分層結果。

這是我的功能結構:

el('root', function(){

  el('users', function(){
    el('show');
  });

  el('products');

});

我想要的結果是:

assert.equal(result, [ 'root', 'root_users', 'root_users_show', 'root_products' ] );

我在實現方面做得很遠: http//jsfiddle.net/5ur5u/我遇到的問題是每次調用el時我都會增加深度。 它工作正常,直到它到達產品。 因為show將深度放在3上意味着產品將在show結束時添加。

所以,如果有人可以幫助我,或指出我正確的方向,那將是偉大的。

你很近。 你只需要在最后減少深度。 http://jsfiddle.net/Z2qsy/

而不是

depth += 1;
fn();

做這個

depth += 1;
fn();
depth -= 1;

由於el在每次調用時都是相同的函數,因此無法區分它在一個級別( show )或另一個級別( products )中被調用。 你可以在每次調用el增加級別,但是沒有辦法知道何時減少它,因為沒有類似於在JavaScript中調用的“相反”。

稍微好一點的選擇是將新函數傳遞給回調(你可以給它命名為el ),這是不同的,這樣每個級別都有自己的el函數。 這樣,結果可以正確構建: http//jsfiddle.net/5ur5u/2/

var result = [];

function el(name, fn) {
    result.push(name); // add current name

    if(fn) { // if there is a function
        fn(function(name2, fn2) { // call the function with a new function
            el(name + "_" + name2, fn2); // which calls `el` recursively
                                         // with the names combined
        });
    }
}

el('root', function(el) {

  // this `el` refers to the function passed as declared above,
  // which is not the same one as the initial `el`
  el('users', function(el) {
    el('show');
  });

  el('products');

});

這就是你所要求的

var names = [];
var result = [];

function el(name, f)
{
    names.push(name);
    result.push(names.join("_"));
    f && f();
    names.pop();
}

el("root", function(){
    el("users", function(){
        el("show")
    });
    el("products");
});

alert(result);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM