在链中进行回调?

Making a callback in a chain?

我们可以在这样的链中进行回调吗?

Widget.update(...).onUpdate(function(data){
   console.log('updated');
});

当前代码,

var Gateway = {};

Gateway.put = function(url, data, callback) {

    $.ajax({
        type: "POST",
        dataType: "xml",
        url: url,
        data: data,
        async: true,
        success: function (returndata,textStatus, jqXHR) {
            callback(returndata);
        }
    });
};


var Plugin = function() {};

Plugin.prototype = {

    update : function(options, callback) {
        /// other stuff
        Gateway.put($url, $data, function(data){
            callback(data);
        }

        return this;
    }
}

用法,

    var Widget = new Plugin();

    Widget.put({
        button: options.button
    }, function(data){
        console.log('updated');
    });

但理想情况下,

Widget.update(...).onUpdate(function(data){
       console.log('updated');
    });

编辑:

jsfiddle

您尝试执行的操作会起作用,但是您需要将回调传递给更新

Widget.update(yourOptions, function(data){
       console.log('updated');
    });

您也可以 return 您的 ajax 请求直接链接到它

var Gateway = {};

Gateway.put = function(url, data) {
    return $.ajax({
        type: "POST",
        dataType: "xml",
        url: url,
        data: data,
        async: true
    });
};


var Plugin = function() {};

Plugin.prototype = {

    update : function(options) {
        /// other stuff
        return Gateway.put($url, $data);
    }
}

var Widget = new Plugin();

Widget.update(yourOptions).done(function() {
  console.log('updated');
});

我真的很喜欢回调地狱编码风格,但有时它会很痛。根据其他用户的建议,您是否已经听说过 promises

The core idea behind promises is that a promise represents the result of an asynchronous operation.

正如上面 link 中所建议的那样 - 为他们提出了一个标准 - 一旦使用

对浏览器进行了 polyfill
<script src="https://www.promisejs.org/polyfills/promise-done-6.1.0.min.js"></script>

您将能够创建 new Promise,因此可以使用它们很好的 done() 属性。

你最终会得到

Plugin.prototype.update = function (options) {
    return new Promise(function (fullfill, reject) {
        Gateway.put($url, $data, function (data) {
            fullfill(data);
        });
    });
};

也就是Plugin.prototype.updatereturns一个承诺。

Widget.update(...).done(function(data){
    console.log('updated');
});

我没有测试过代码,但精神就是这样。 :)

编辑:使用 promises 很棒。我只是不喜欢人们发现它们,在代码库的较新部分使用它们,但最终不重构其余部分。