有没有更好的方法来做回调链在javascript? [英] Is there a better way to do callback chaining in javascript?

查看:98
本文介绍了有没有更好的方法来做回调链在javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个回调助手,让我将多个回调组合成一个函数变量:

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);
            }
        }
    };
}

这可行,但我想知道是否有任何JavaScript库相同的功能?或者甚至更好,模拟.NET事件模式的东西?

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;


推荐答案

我已经修改了chainCallbacks函数。您可以在JS控制台中测试以下代码(我使用Chrome -works精细),并检查结果。

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();

想法很简单 - 你调用 _next()每当你的回调函数完成执行,并且你想跳到另一个。所以你可以调用 _next()例如。在一些jQuery动画之后,这样你将保留函数的顺序。

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.

这篇关于有没有更好的方法来做回调链在javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆