tomsseisums
tomsseisums

Reputation: 13367

Callback execution only on last in stack

Currently I've set it up like this,

var elements = $('#one, $two, #three, #four, #six');

var _temp = 0;
elements.hide(0, function(){
    /* by default, the callback will be performed to
       every single element in stack */

    _temp++; // increment temporary cache

    // perform actual callback only on last in list
    if (_temp == elements.length) {
        // do stuff
    }
});

but it feels wrong, because if I'd want to do the same for another callback 241 lines below, I'd have to reset _temp and well, global variables are just messy.

How could I simplify this?

Upvotes: 1

Views: 78

Answers (3)

tomsseisums
tomsseisums

Reputation: 13367

There is also another way without temporary variable, it may be a little less readable for some, and forces you to store your selection inside a variable, but:

elements.hide(0, function(){
    // if last callback (compare raw DOMElements, because jQuery object aren't somehow similar)
    if ($(this)[0] === elements.last()[0]) {
        // do stuff
    }
});

Narrows down some lines, and does the trick.

Upvotes: 0

Zeta
Zeta

Reputation: 105885

One possible way is to use a closure:

var elements = $('#one, $two, #three, #four, #six');

elements.hide(0, (function(){
    var _temp = 0;
    return function(){
        _temp++; // increment temporary cache

        // perform actual callback only on last in list
        if (_temp == elements.length) {
            // do stuff
        }
    };
})());

If you want to use this pattern more often you could create a function which returns a callback.

Also note that .hide() has a duration as first argument.

Upvotes: 3

Chefire
Chefire

Reputation: 139

Try using a static variable in your function.

Upvotes: 1

Related Questions