How to implement reusable callback functions

我的梦境 提交于 2019-12-04 04:11:51

In general, there is no getting around having to create another function in-line that has access to the closures. You can create the function in-line by having a simple anonymous function that passes some arguments to the parent callback as parameters while accepting the rest (i.e. a partial function), or by using Function.bind() to create the partial function itself.

For example, if you initially had:

function(...) {
    // closure vars x1, y1
    foo.bar( function(result) {
        // do something with x1 and y1
    });
}

You could extract that to:

var callback = function(x1, y1, result) {
    // do something with x1 and y1
};

function(...) {
    // closure vars x1, y1

    // option 1: make your own partial function
    foo.bar( function(result) { return callback(x1, y1, result); });
    // with ES6: foo.bar( (result) => callback(x1, y1, result); });

    // option 2: use Function.bind
    foo.bar( callback.bind(this, x1, y1); );
}

here is a nested callback example with no closure and no nesting. it grabs the page specified, finds the third link, then shows the source of that link to the user.

in this case, when run from here in the console and fed the home page, the logout page is the third link, and it's contents are alerted.

all the callbacks are siblings, and there are no outside state variables, just pure functional async:

// look ma, no nesting!
function ajax(a, c) {
    var e = new XMLHttpRequest;
    e.onload= ajaxOnload.bind(this, c, e);
    e.open( "GET", a, !0);
    e.send();
    return e
}

function ajaxOnload(c, e) {
    c(e.responseText, e);
}

function cbFind3(cb, s){
    var t=document.createElement("body");
    t.innerHTML=s;
    var lnk= t.getElementsByTagName("a")[3].href;
    ajax(lnk, cb);    
}

function grabThirdLinkSource(url, cb){
  ajax(url, cbFind3.bind(this, cb));
}

grabThirdLinkSource("/", alert);

it's not the most useful example, but it does show how to chain functions across invocations with bind(). i used vanilla ajax and avoided promises simply to show how this style of interaction performs without any complications. even the ajax helper uses a non-nested function to feed responseText to the "core" callbacks instead of the event or whole xhr object.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!