kenneth koontz
kenneth koontz

Reputation: 869

using jQuery deferred objects to work with a jQuery collection/array serially

I have an array of jQuery objects. I'd like to interact with each item in the array if they are visible. My flow goes something like this:

  1. Create an array, whose elements are all jQuery objects.
  2. The objects may or may not be visible.
  3. Start with the first element in the array.
  4. Wait for the item to be visible, time is arbitrary. Say 3 seconds. If becomes visible, go to step 5, else return from 'play' function. // Updated
  5. Click the item.
  6. Repeat 4-5 until there are no more items left to be interacted with.

UPDATE (clarification of use case):
Essentially what I'm doing is performing a series of serial actions on an array. A-B-C-D, in order. However there may be an issue when A creates B's element and B has already been checked if it was visible. It won't get clicked on.

I've been looking at jQuery's deferred object, but am at a loss on how to implement it. How can this be implemented? Is there an alternative to using a deferred object?

As per @jmort's suggestion I'll attach what I have so far.

var play = function() {
    var dfds = []; 
    $(steps).each(function(i, v) {
        dfds[i] = $.Deferred();
    }); 

    $.when.apply(null, dfds).then(function(){
        console.log('all done');
    }); 

};  

Assume that steps equals the array of jQuery objects.

Upvotes: 2

Views: 356

Answers (1)

gdoron
gdoron

Reputation: 150313

It can be done easily:

var play = function() {
    $(steps).filter(':visible').click();
}; 

Update:

var play = function() {
    $(steps).each(function() {
        $(this).filter(':visible').click();
    });
};​

Upvotes: 2

Related Questions