2 Copyright (c) 2010, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
8 YUI.add('async-queue', function(Y) {
11 * <p>AsyncQueue allows you create a chain of function callbacks executed
12 * via setTimeout (or synchronously) that are guaranteed to run in order.
13 * Items in the queue can be promoted or removed. Start or resume the
14 * execution chain with run(). pause() to temporarily delay execution, or
15 * stop() to halt and clear the queue.</p>
21 * <p>A specialized queue class that supports scheduling callbacks to execute
22 * sequentially, iteratively, even asynchronously.</p>
24 * <p>Callbacks can be function refs or objects with the following keys. Only
25 * the <code>fn</code> key is required.</p>
28 * <li><code>fn</code> -- The callback function</li>
29 * <li><code>context</code> -- The execution context for the callbackFn.</li>
30 * <li><code>args</code> -- Arguments to pass to callbackFn.</li>
31 * <li><code>timeout</code> -- Millisecond delay before executing callbackFn.
32 * (Applies to each iterative execution of callback)</li>
33 * <li><code>iterations</code> -- Number of times to repeat the callback.
34 * <li><code>until</code> -- Repeat the callback until this function returns
35 * true. This setting trumps iterations.</li>
36 * <li><code>autoContinue</code> -- Set to false to prevent the AsyncQueue from
37 * executing the next callback in the Queue after
38 * the callback completes.</li>
39 * <li><code>id</code> -- Name that can be used to get, promote, get the
40 * indexOf, or delete this callback.</li>
44 * @extends EventTarget
46 * @param callback* {Function|Object} 0..n callbacks to seed the queue
48 Y.AsyncQueue = function() {
50 this.add.apply(this, arguments);
53 var Queue = Y.AsyncQueue,
59 isObject = Y.Lang.isObject,
60 isFunction = Y.Lang.isFunction;
63 * <p>Static default values used to populate callback configuration properties.
64 * Preconfigured defaults include:</p>
67 * <li><code>autoContinue</code>: <code>true</code></li>
68 * <li><code>iterations</code>: 1</li>
69 * <li><code>timeout</code>: 10 (10ms between callbacks)</li>
70 * <li><code>until</code>: (function to run until iterations <= 0)</li>
73 * @property AsyncQueue.defaults
77 Queue.defaults = Y.mix({
83 return this.iterations <= 0;
85 }, Y.config.queueDefaults || {});
87 Y.extend(Queue, Y.EventTarget, {
89 * Used to indicate the queue is currently executing a callback.
92 * @type {Boolean|Object} true for synchronous callback execution, the
93 * return handle from Y.later for async callbacks.
100 * Initializes the AsyncQueue instance properties and events.
105 _init : function () {
106 Y.EventTarget.call(this, { emitFacade: true });
111 * Callback defaults for this instance. Static defaults that are not
112 * overridden are also included.
123 * Initializes the instance events.
125 * @method _initEvents
128 _initEvents : function () {
130 'execute' : { defaultFn : this._defExecFn, emitFacade: true },
131 'shift' : { defaultFn : this._defShiftFn, emitFacade: true },
132 'add' : { defaultFn : this._defAddFn, emitFacade: true },
133 'promote' : { defaultFn : this._defPromoteFn, emitFacade: true },
134 'remove' : { defaultFn : this._defRemoveFn, emitFacade: true }
139 * Returns the next callback needing execution. If a callback is
140 * configured to repeat via iterations or until, it will be returned until
141 * the completion criteria is met.
143 * When the queue is empty, null is returned.
146 * @return {Function} the callback to execute
151 while (this._q.length) {
152 callback = this._q[0] = this._prepare(this._q[0]);
153 if (callback && callback.until()) {
154 this.fire(SHIFT, { callback: callback });
161 return callback || null;
165 * Default functionality for the "shift" event. Shifts the
166 * callback stored in the event object's <em>callback</em> property from
167 * the queue if it is the first item.
169 * @method _defShiftFn
170 * @param e {Event} The event object
173 _defShiftFn : function (e) {
174 if (this.indexOf(e.callback) === 0) {
180 * Creates a wrapper function to execute the callback using the aggregated
181 * configuration generated by combining the static AsyncQueue.defaults, the
182 * instance defaults, and the specified callback settings.
184 * The wrapper function is decorated with the callback configuration as
185 * properties for runtime modification.
188 * @param callback {Object|Function} the raw callback
189 * @return {Function} a decorated function wrapper to execute the callback
192 _prepare: function (callback) {
193 if (isFunction(callback) && callback._prepared) {
197 var config = Y.merge(
199 { context : this, args: [], _prepared: true },
201 (isFunction(callback) ? { fn: callback } : callback)),
203 wrapper = Y.bind(function () {
204 if (!wrapper._running) {
205 wrapper.iterations--;
207 if (isFunction(wrapper.fn)) {
208 wrapper.fn.apply(wrapper.context || Y,
209 Y.Array(wrapper.args));
213 return Y.mix(wrapper, config);
217 * Sets the queue in motion. All queued callbacks will be executed in
218 * order unless pause() or stop() is called or if one of the callbacks is
219 * configured with autoContinue: false.
222 * @return {AsyncQueue} the AsyncQueue instance
229 for (callback = this.next();
230 cont && callback && !this.isRunning();
231 callback = this.next())
233 cont = (callback.timeout < 0) ?
234 this._execute(callback) :
235 this._schedule(callback);
240 * Event fired after the last queued callback is executed.
243 this.fire('complete');
250 * Handles the execution of callbacks. Returns a boolean indicating
251 * whether it is appropriate to continue running.
254 * @param callback {Object} the callback object to execute
255 * @return {Boolean} whether the run loop should continue
258 _execute : function (callback) {
259 this._running = callback._running = true;
261 callback.iterations--;
262 this.fire(EXECUTE, { callback: callback });
264 var cont = this._running && callback.autoContinue;
266 this._running = callback._running = false;
272 * Schedules the execution of asynchronous callbacks.
275 * @param callback {Object} the callback object to execute
276 * @return {Boolean} whether the run loop should continue
279 _schedule : function (callback) {
280 this._running = Y.later(callback.timeout, this, function () {
281 if (this._execute(callback)) {
290 * Determines if the queue is waiting for a callback to complete execution.
293 * @return {Boolean} true if queue is waiting for a
294 * from any initiated transactions
296 isRunning : function () {
297 return !!this._running;
301 * Default functionality for the "execute" event. Executes the
305 * @param e {Event} the event object
308 _defExecFn : function (e) {
313 * Add any number of callbacks to the end of the queue. Callbacks may be
314 * provided as functions or objects.
317 * @param callback* {Function|Object} 0..n callbacks
318 * @return {AsyncQueue} the AsyncQueue instance
322 this.fire('add', { callbacks: Y.Array(arguments,0,true) });
328 * Default functionality for the "add" event. Adds the callbacks
329 * in the event facade to the queue. Callbacks successfully added to the
330 * queue are present in the event's <code>added</code> property in the
334 * @param e {Event} the event object
337 _defAddFn : function(e) {
341 Y.Array.each(e.callbacks, function (c) {
352 * Pause the execution of the queue after the execution of the current
353 * callback completes. If called from code outside of a queued callback,
354 * clears the timeout for the pending callback. Paused queue can be
355 * restarted with q.run()
358 * @return {AsyncQueue} the AsyncQueue instance
362 if (isObject(this._running)) {
363 this._running.cancel();
366 this._running = false;
372 * Stop and clear the queue after the current execution of the
373 * current callback completes.
376 * @return {AsyncQueue} the AsyncQueue instance
386 * Returns the current index of a callback. Pass in either the id or
387 * callback function from getCallback.
390 * @param callback {String|Function} the callback or its specified id
391 * @return {Number} index of the callback or -1 if not found
393 indexOf : function (callback) {
394 var i = 0, len = this._q.length, c;
396 for (; i < len; ++i) {
398 if (c === callback || c.id === callback) {
407 * Retrieve a callback by its id. Useful to modify the configuration
408 * while the queue is running.
410 * @method getCallback
411 * @param id {String} the id assigned to the callback
412 * @return {Object} the callback object
414 getCallback : function (id) {
415 var i = this.indexOf(id);
417 return (i > -1) ? this._q[i] : null;
421 * Promotes the named callback to the top of the queue. If a callback is
422 * currently executing or looping (via until or iterations), the promotion
423 * is scheduled to occur after the current callback has completed.
426 * @param callback {String|Object} the callback object or a callback's id
427 * @return {AsyncQueue} the AsyncQueue instance
430 promote : function (callback) {
431 var payload = { callback : callback },e;
433 if (this.isRunning()) {
434 e = this.after(SHIFT, function () {
435 this.fire(PROMOTE, payload);
439 this.fire(PROMOTE, payload);
446 * <p>Default functionality for the "promote" event. Promotes the
447 * named callback to the head of the queue.</p>
449 * <p>The event object will contain a property "callback", which
450 * holds the id of a callback or the callback object itself.</p>
452 * @method _defPromoteFn
453 * @param e {Event} the custom event
456 _defPromoteFn : function (e) {
457 var i = this.indexOf(e.callback),
458 promoted = (i > -1) ? this._q.splice(i,1)[0] : null;
460 e.promoted = promoted;
463 this._q.unshift(promoted);
468 * Removes the callback from the queue. If the queue is active, the
469 * removal is scheduled to occur after the current callback has completed.
472 * @param callback {String|Object} the callback object or a callback's id
473 * @return {AsyncQueue} the AsyncQueue instance
476 remove : function (callback) {
477 var payload = { callback : callback },e;
479 // Can't return the removed callback because of the deferral until
480 // current callback is complete
481 if (this.isRunning()) {
482 e = this.after(SHIFT, function () {
483 this.fire(REMOVE, payload);
487 this.fire(REMOVE, payload);
494 * <p>Default functionality for the "remove" event. Removes the
495 * callback from the queue.</p>
497 * <p>The event object will contain a property "callback", which
498 * holds the id of a callback or the callback object itself.</p>
500 * @method _defRemoveFn
501 * @param e {Event} the custom event
504 _defRemoveFn : function (e) {
505 var i = this.indexOf(e.callback);
507 e.removed = (i > -1) ? this._q.splice(i,1)[0] : null;
511 * Returns the number of callbacks in the queue.
517 // next() flushes callbacks that have met their until() criteria and
518 // therefore shouldn't count since they wouldn't execute anyway.
519 if (!this.isRunning()) {
523 return this._q.length;
529 }, '3.3.0' ,{requires:['event-custom']});