Dummy example of using queues with _.delay
HTML
<script src="http://underscorejs.org/underscore-min.js"></script>
JavaScript
window.q = $({});
foo = {
_init: function(context, settings) {
// Doing things in here..
document.write(settings.toString());
document.write('<br />');
},
init: function(context, settings) {
_this = foo;
// Do some validation before initialising.
// ...
// Initialise.
_this._init(context, settings);
// $().dequeue() here is the same as calling
// next() within original queue() closure.
window.q.dequeue('default');
}
};
bar = function(input) {
// Let everyone know that bar was here.
document.write(input);
// There's no harm in calling dequeue()
// on an empty queue.
window.q.dequeue('default');
}
// Document ready.
$(function() {
fooContext = $('#content');
fooSettings = {
a: 'b',
c: {
d: 'e'
}
};
// Create/use a queue on the body element.
// Queues can be added to *any* jQuery object, even just $({});
window.q.queue('default', function(next) {
_.delay(foo.init, 12, fooContext, fooSettings);
});
window.q.queue('default', function(next) {
_.delay(bar, 5000, "<br/>after 5 seconds");
_.delay(bar, 10000, "<br/>after 10 seconds");
_.delay(bar, 15000, "<br/>after 15 seconds");
document.write("<br/>ended!");
});
// Uncommenting this will overwrite our settings because
// the values in the scope of our queue are not set
// until dequeue() is called. Be careful.
// fooSettings = 'fail';
// Start processing the queue.
window.q.dequeue('default');
// _.delay protects us from this overwriting our settings object
// *after* dequeue() has been called, which can lead to nasty
// bugs when working with setTimeout().
fooSettings = 'fail';
});