I have a HTML document with the following markup:
<div id="outside">
<div id="warning">Some warning here</div>
<div id="inside"></div>
</div>
What I would like to do is this list of things, in the order listed, without proceeding to the next item before the prior is complete:
- Hide the #outside element.
- Set the contents of #inside to “foo”.
- Show the #outside element.
Something like this could be done with jQuery:
$('#outside').hide(function(){
$('#inside').html('bar');
$('#outside').show();
});
This code gets more confusing as more events include callbacks, and becomes not easily maintainable.
Instead, I would like to do something like this:
$.sequence(
function(){ $('#outside').hide(); },
function(){ $('#inside').html('foo'); },
function(){ $('#outside').show(); }
);
This code clearly shows each step of the process, and allows easy insertion/removal of any step because it doesn’t require nested function callbacks.
Note that the HTML shown here is radically simplified from what I am actually using, and the chain of actions I would like to apply to those elements longer.
Normally, this would be possible merely with sequential method calls on the same jQuery element, but there are different elements in use which don’t allow the queues to execute in order. I’m looking for a way to sequence calls that looks clean when read and works with any elements.
In this particular example, It’s relatively easy. You can get your desired results with:
However, if you throw in asynchrounous events, this obviously won’t work. Lets say you instead wanted to get ‘foo’ with ajax. This would be a relatively common way of doing it.
Nothing about that is hard to read unless you just aren’t used to using deferred objects. It results in a small amount of code that retrieves and displays the content as fast as possible with subtle animations.
You could of course abstract this method behind a function if you REALLY want to make it “look better”, but it may end up being less maintainable (Where did i define that function?)