javascript调用具有相同上下文

时间:2016-12-14 14:52:21

标签: javascript arrays middleware

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

这是我提出的代码:

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功能。它就像一个中间件。

2 个答案:

答案 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);

答案 1 :(得分:1)

您的next函数实际上不一定是链中的下一个函数。

它打算运行下一个函数。

&#13;
&#13;
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);
&#13;
&#13;
&#13;