Reputation: 13367
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
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
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