JQuery promises: Is there a reusable alternative?

I am creating a web application that has a set of functions that the user can perform several times, but requires enough asynchronous actions for callbacks to get a little out of control.

What are realistic alternatives $.Defferedand $.whenthat can be "used" several times?

  • I am not looking for a full-blown infrastructure.
  • I do not want to use callbacks (directly)

Thank!

+5
source share
3 answers

I think you are looking for events. JQuery example using on and trigger

var data_handler = $({});

function get_data(new_foo) {
   // Do stuff, then send the event
   data_handler.trigger('new_data', {foo: new_foo});
}

data_handler.on('new_data', function(e, data) {
   console.log('Handler 1: ' + data.foo);
});

data_handler.on('new_data', function(e, data) {
   console.log('Handler 2: ' + data.foo);
});

get_data(1);
get_data(2);

Conclusion:

Handler 1: 1
Handler 2: 1
Handler 1: 2
Handler 2: 2
+2
source

Here are 3 such libraries:

. promises.

+1

, , , Ajax, :

var cycle = function(func, interval){
    var _this = this;

    // Use jQuery triggers to manage subscriptions
    var o = $({});
    this.publish = o.trigger.bind(o);
    this.subscribe = o.on.bind(o);
    this.unsubscribe = o.off.bind(o);

    var call = function(func){

        clearTimeout(_this.timeout);

        func().done(function(response){
            _this.publish('ajax:update', response);
            _this.timeout = setTimeout(function(){
                call(func);
            }, interval);
        });
    };
    call(func);

    return this;
};

var ajax_promise = function(){
    return $.getJSON('http://localhost/some/data.json');
};

var my_callback = function(response){
    // Do stuff
};

cycle(ajax_promise, 10000).subscribe('ajax:update', my_callback);
0
source

All Articles