Is there a better way to do callback chaining in j

2019-02-25 05:19发布

I wrote a callback helper, that lets me group multiple callbacks into one function variable:

function chainCallbacks() {
    var callbacks = arguments;
    return function () {
        for(var i = 0; i < callbacks.length; i++) {
            if(callbacks[i] != null) {
                callbacks[i].apply(null, arguments);
            }
        }
    };
}

this works, but I'm wondering if there are any javascript libraries that provide the same functionality? or even better, something that simulates the .NET "event" pattern?

myEvent+=myCallback;

2条回答
Rolldiameter
2楼-- · 2019-02-25 05:49

I have modified your chainCallbacks function. You can test below code in JS console (I'm using Chrome -works fine), and check the result.

var result = 0;

function a() {
        result += 5;
        console.log(result);
        _next();
}

function b() {
        result += 10;
        console.log(result);
        _next();
}

function c() {
        result += 20;
        console.log(result);
        _next();
}

function chainCallbacks() {

    var _this = this;
    var _counter = 0;
    var _callbacks = arguments;

    var _next = function() {
        _counter++;
        if(_counter < _callbacks.length) {
            _callbacks[_counter].apply(_this);
        }
    };

    _this._next = _next;

    return function() {
        if(_callbacks.length > 0) {
            _callbacks[0].apply(_this);
        }
    };
}

var queue = chainCallbacks(a, b, c);
queue();

Idea is simple - you call _next() whenever your callback function has finished executing, and you want to jump to another. So you can call _next() e.g. after some jQuery animation as well, and this way you will preserve the order of the functions.

查看更多
The star\"
3楼-- · 2019-02-25 05:59

If you want to replace a callback with one that calls the original as well as some others, I'd probably just do something like this:

Requirejs.config.callback = function(orig) {
    var fns = [orig, first, second, third];
    return function() {
        fns.forEach(function(fn) { fn.apply(null, this); }, arguments);
    };
}(Requirejs.config.callback);

But if you're doing this often, I think your solution will be as good as it gets. I don't see need for a library.

Requirejs.config.callback = chainCallbacks(Requirejs.config.callback, first, second, third)

A library can't do anything to extend language syntax in JavaScript. It's limited to what's available... no operator overloading or anything.

查看更多
登录 后发表回答