Run
Run

Reputation: 57276

Making a callback in a chain?

Can we make a callback in a chain like this?

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

current code,

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

usage,

    var Widget = new Plugin();

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

but ideally,

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

EDIT:

at jsfiddle.

Upvotes: 0

Views: 92

Answers (2)

Giuseppe Crinò
Giuseppe Crinò

Reputation: 546

I really like the callback hell coding style, but sometimes it hurts. As suggested by other users, have you already heard about promises?

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

As suggested in the link above - that proposed a standard for them - once polyfill'd the browser using

<script src="https://www.promisejs.org/polyfills/promise-done-6.1.0.min.js"></script>

you will be able to create new Promise's, hence to use their nice done() attribute.

You will end up with

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

That is, Plugin.prototype.update returns a promise.

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

I have not tested the code, but the spirit is that. :)

EDIT: Using promises is awesome. I simply don't like when people discover them, use them in newer parts of the codebase but finally do not refactor the rest of it.

Upvotes: 1

Simon Staton
Simon Staton

Reputation: 4505

What you are trying to do will work however you need to pass your callback to update

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

You could also return your ajax request directly and chain onto it

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

Upvotes: 2

Related Questions