2016-12-14 49 views
2

我正在尝试创建一个回调函数,或者至少这是我如何命名它。主要目的是从具有相同上下文的数组中调用函数,并能够从当前正在执行的函数中调用数组中的下一个函数。javascript调用具有相同上下文的函数数组

这是我想出了代码:

function callCallbackChain(context, callbackChain, params) { 
 
    callbackChain.push(function() { 
 
     return true; 
 
    }); 
 
    for (var i = 0, len = callbackChain.length - 1; i < len; i++) { 
 
     var cb = callbackChain[i]; 
 
     var next = callbackChain[i + 1]; 
 
     if (typeof cb === "function") { 
 
      cb.apply(context, [next].concat(params)); 
 
     } 
 
    } 
 
} 
 
var callbackChain = [ 
 
    function (next, foo) { 
 
     console.log('1 function call', arguments); 
 
     this.innerHTML = this.innerHTML + "function called + context:" + foo + "<br>"; 
 
     next() 
 
    }, 
 
    function (next, foo) { 
 
     console.log('2 function call', arguments); 
 
     this.innerHTML = this.innerHTML + "function called + context:" + foo + "<br>"; 
 
     next() 
 
    }, 
 
    function (next, foo) { 
 
     console.log('3 function call', arguments); 
 
     this.innerHTML = this.innerHTML + "function called + context:" + foo + "<br>"; 
 
     next() 
 
    } 
 
]; 
 

 

 
var d = document.querySelector("#conent"); 
 
callCallbackChain(d, callbackChain, ["param from the main function"]);
<div id="conent"> 
 
    Initial Content 
 
    
 
</div>

我似乎无法能够正确设置next功能。它就像一个中间件。

回答

1

next功能不能实际上是链中的一个功能。

它的目的是运行下一个功能。

function run(context, chain, params) { 
 
    var inner_run = (context, chain, params, index) => { 
 
    next =() => inner_run(context, chain, params, index + 1); 
 
    if (index < chain.length) chain[index].apply(context, [next].concat(params)); 
 
    }; 
 
    inner_run(context, chain, params, 0); 
 
} 
 

 
var chain = [ 
 
    function (next, foo) { 
 
    this.first = true 
 
    console.log('first', arguments); 
 
    next() 
 
    }, 
 
    function (next, foo) { 
 
    this.second = true 
 
    console.log('second', arguments); 
 
    // not calling next() 
 
    }, 
 
    function (next, foo) { 
 
    this.third = true 
 
    console.log('third', arguments); 
 
    next() 
 
    } 
 
]; 
 

 
var context = {}; 
 

 
run(context, chain, ["param"]); 
 

 
console.log('context', context);

+1

这一个实际上适用于我。我已经完成了我的版本,但这是完整的工作答案,所以我会接受它。 – melanholly

+0

不错的工作...... –

1

你需要将它绑定在飞行:

var nextelem=0; 
function next(params...){ 
temp=nextelem; 
nextelem++; 
callbackChain[temp].bind(context)(next,...params); 
} 
//pass it 
nextelem=1; 
callbackChain[0].bind(context)(next); 
+0

我仍然得到'undefined'背景https://jsfiddle.net/xr8q7s1f/2/ – melanholly

+0

中的第一个香港专业教育学院错过了接下来的部分,尝试第二... –

+0

下一个函数需要是递归的,所以你需要传递一个非常复杂的函数。动态生成它应该更容易... –

相关问题