如何覆盖jQuery promise回调 [英] How to override jQuery promise callback

查看:73
本文介绍了如何覆盖jQuery promise回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个方便的方法,为我的ajax调用添加了一个默认的错误处理程序:

I've created a convenience method that adds a default error handler for my ajax calls:

function myAjaxFunction(url, data) {

    return $.ajax({
        url: url,
        data: data

    }).fail(myErrorHandler);

}

到目前为止,这很有效,因为现在我不喜欢必须在50个不同的地方指定错误处理函数。

So far, this works great, because now I don't have to specify the error handler function in 50 different places.

但有时我需要使用自定义错误处理程序覆盖默认错误处理程序。但是,当我这样做时,它会调用两个错误处理程序:

But sometimes I need to override the default error handler with a custom one. When I do this, however, it calls both error handlers:

myAjaxFunction("myurl", "mydata").fail(myCustomErrorHandler).then(doSomething);

如何让它覆盖或删除链中的先前错误处理程序?

How do I get it to override or remove the previous error handler from the chain?

推荐答案


如何从链中删除以前的错误处理程序?

How do I get it to remove the previous error handler from the chain?

你不能。


或覆盖它?

or override it?

你可以撤消它的作用(覆盖它的效果)。但是,您应该最好避免添加常规处理程序 - 为此,您必须更改便捷方法。我建议将自定义处理程序作为可选参数:

You could undo what it did (overriding its effects). However, you should better avoid adding the general handler at all - to do that, you will have to change your convenience method. I'd recommend a custom handler as an optional parameter:

function myAjaxFunction(url, data, customHandler) {
    return $.ajax({
        url: url,
        data: data

    }).fail(customHandler || myErrorHandler);
}

这篇关于如何覆盖jQuery promise回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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