Is there a better way to do callback chaining in javascript?

后端 未结 2 867
北海茫月
北海茫月 2021-01-20 16:13

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

function chainCallbacks() {
    var callbacks = arguments;
    r         


        
2条回答
  •  后悔当初
    2021-01-20 16:51

    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.

提交回复
热议问题