0

我正在用 jQuery 制作一个 ajax 包装器,但是我在正确处理范围时遇到了一些问题。(为了便于阅读,代码被缩短)

我有一个我想在 beforeSend 事件中使用的实用程序类,但它目前未定义。我尝试使用 call() 方法向下传递范围,但这并没有改变任何东西。

我怎么能做到这一点?

class AjaxHelper{
private _utils: Utilities;
AjaxCall(options: AjaxHelperOptions)
{
    this._utils = new Utilities();

    var defaults: AjaxHelperOptions = { ... };
    var settings: AjaxHelperOptions = $.extend({}, defaults, options);

    var deferred = $.Deferred.call(this, function (d) {

        d.done(settings.success);
        d.fail(settings.error);
        d.done(settings.complete);

        var jqXHRSettings = $.extend.call(this, {}, settings, {

            beforeSend: function (jqXHR, settings) {
            ______________________________________
            this._utils.CallSomeUtilityFunction();
            ______________________________________

                d.resolve;
            }

             .......................

            $.ajax.call(this, jqXHRSettings);
    });

    var promise: JQueryPromise = deferred.promise();

    promise.done = deferred.done;
    promise.fail = deferred.fail;

    return promise;
}
}
4

2 回答 2

1

您需要this在整个链中维护功能范围:

var deferred = $.Deferred.call(this, (d) => { // this line

        d.done(settings.success);
        d.fail(settings.error);
        d.done(settings.complete);

        var jqXHRSettings = $.extend.call(this, {}, settings, {

            beforeSend: (jqXHR, settings) =>  { // AND this line
            ______________________________________
            this._utils.CallSomeUtilityFunction();
            ______________________________________

                d.resolve;
            }

             .......................

            $.ajax.call(this, jqXHRSettings);
    });
于 2013-07-11T22:19:46.233 回答
0

尝试使用这样的 lambda 函数:

beforeSend: (jqXHR, settings) => {
    this._utils.CallSomeUtilityFunction();
    d.resolve;
}
于 2013-07-11T17:18:51.727 回答