What I want to do is; without leaving the chain, execute some custom/external code (and continue) within the chain. Otherwise; in a deep chain, I will have to re-query for the DOM element to get back where I've left.
The method below allows to execute custom code inside a jQuery chain synchronously or asynchronously.
//Execute code inside a jQuery chain
$.fn.do = function (callback, async) {
if (typeof callback === 'function') {
if (async === true) {
this.queue(function() {
callback($(this));
$(this).dequeue();
});
} else {
callback(this);
}
}
return this;
};
Simplified Usage Example:
var results = {};
$('#some-elem')
.css({
//modify some styles here
})
.do(function($elem) {
//do some calculations.. tests here..
//save them to results object
}, false) //synchronous
.css({
//re-set the styles back to their initial state
});
This could be a longer chain where you could need to enter the do()
method multiple times.
So;
- Do you think the approach above is legitimate?
- Would you suggest an alternate? Why?
.queue()
here - why are you adding a function to the defaultfx
queue (will be queued after animations when there are pending animations) if this version of the method is asynchronous? You can probably get rid of that. \$\endgroup\$do()
method) so I'm allowing for both async and immediate execution. (I'm also passing the corresponding jQuery element as an argument.) Does it make sense? \$\endgroup\$.css()
should wait untildo()
callsdequeue()
? \$\endgroup\$.css()
method is executed immediately and.do()
is called withfalse
param. And essentially,do(func, true)
(async) is only a shorhand forqueue()
which will execute when it's his turn in the queue. You might say that I'm only extending the.queue()
method with a sync execution capability. \$\endgroup\$queue
then this looks perfectly fine. I may take another look tomorrow but there isn't much code to cut out without losing a lot of readability. \$\endgroup\$