Haroldo
Haroldo

Reputation: 37377

jQuery promises: Is there a reusable alternative?

I'm building a web app which has a set of functions that the user may perform a few times but involve enough asynchronous actions for callbacks to get a bit out of hand.

What are realistic alternatives to $.Deffered and $.when that can be 'used' multiple times?

Upvotes: 5

Views: 2407

Answers (3)

Izkata
Izkata

Reputation: 9323

I think what you're looking for are events. An example in jQuery 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);

Output:

Handler 1: 1
Handler 2: 1
Handler 1: 2
Handler 2: 2

Upvotes: 2

mattwad
mattwad

Reputation: 1980

Instead of attaching to the promise directly, you can make a wrapper around the promise that allows a callback to subscribe to a recurring promise or Ajax call made at a set interval:

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

    // Use jQuery's 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);

Upvotes: 0

MegaHit
MegaHit

Reputation: 2644

Here are 3 such libraries:

  1. Q
  2. rsvp.js
  3. when.js

These libraries are not "full blown". They just implement promises.

Upvotes: 1

Related Questions