2 Copyright (c) 2009, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.net/yui/license.txt
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 () {
131 'execute' : { defaultFn : this._defExecFn },
132 'shift' : { defaultFn : this._defShiftFn },
133 'add' : { defaultFn : this._defAddFn },
134 'promote' : { defaultFn : this._defPromoteFn },
135 'remove' : { defaultFn : this._defRemoveFn }
138 this.publish('execute' , { defaultFn : this._defExecFn, emitFacade: true });
139 this.publish('shift' , { defaultFn : this._defShiftFn, emitFacade: true });
140 this.publish('add' , { defaultFn : this._defAddFn, emitFacade: true });
141 this.publish('promote' , { defaultFn : this._defPromoteFn, emitFacade: true });
142 this.publish('remove' , { defaultFn : this._defRemoveFn, emitFacade: true });
146 * Returns the next callback needing execution. If a callback is
147 * configured to repeat via iterations or until, it will be returned until
148 * the completion criteria is met.
150 * When the queue is empty, null is returned.
153 * @return {Function} the callback to execute
158 while (this._q.length) {
159 callback = this._q[0] = this._prepare(this._q[0]);
160 if (callback && callback.until()) {
161 this.fire(SHIFT, { callback: callback });
168 return callback || null;
172 * Default functionality for the "shift" event. Shifts the
173 * callback stored in the event object's <em>callback</em> property from
174 * the queue if it is the first item.
176 * @method _defShiftFn
177 * @param e {Event} The event object
180 _defShiftFn : function (e) {
181 if (this.indexOf(e.callback) === 0) {
187 * Creates a wrapper function to execute the callback using the aggregated
188 * configuration generated by combining the static AsyncQueue.defaults, the
189 * instance defaults, and the specified callback settings.
191 * The wrapper function is decorated with the callback configuration as
192 * properties for runtime modification.
195 * @param callback {Object|Function} the raw callback
196 * @return {Function} a decorated function wrapper to execute the callback
199 _prepare: function (callback) {
200 if (isFunction(callback) && callback._prepared) {
204 var config = Y.merge(
206 { context : this, args: [], _prepared: true },
208 (isFunction(callback) ? { fn: callback } : callback)),
210 wrapper = Y.bind(function () {
211 if (!wrapper._running) {
212 wrapper.iterations--;
214 if (isFunction(wrapper.fn)) {
215 wrapper.fn.apply(wrapper.context || Y,
216 Y.Array(wrapper.args));
220 return Y.mix(wrapper, config);
224 * Sets the queue in motion. All queued callbacks will be executed in
225 * order unless pause() or stop() is called or if one of the callbacks is
226 * configured with autoContinue: false.
229 * @return {AsyncQueue} the AsyncQueue instance
236 for (callback = this.next();
237 cont && callback && !this.isRunning();
238 callback = this.next())
240 cont = (callback.timeout < 0) ?
241 this._execute(callback) :
242 this._schedule(callback);
247 * Event fired after the last queued callback is executed.
250 this.fire('complete');
257 * Handles the execution of callbacks. Returns a boolean indicating
258 * whether it is appropriate to continue running.
261 * @param callback {Object} the callback object to execute
262 * @return {Boolean} whether the run loop should continue
265 _execute : function (callback) {
266 this._running = callback._running = true;
268 callback.iterations--;
269 this.fire(EXECUTE, { callback: callback });
271 var cont = this._running && callback.autoContinue;
273 this._running = callback._running = false;
279 * Schedules the execution of asynchronous callbacks.
282 * @param callback {Object} the callback object to execute
283 * @return {Boolean} whether the run loop should continue
286 _schedule : function (callback) {
287 this._running = Y.later(callback.timeout, this, function () {
288 if (this._execute(callback)) {
297 * Determines if the queue is waiting for a callback to complete execution.
300 * @return {Boolean} true if queue is waiting for a
301 * from any initiated transactions
303 isRunning : function () {
304 return !!this._running;
308 * Default functionality for the "execute" event. Executes the
312 * @param e {Event} the event object
315 _defExecFn : function (e) {
320 * Add any number of callbacks to the end of the queue. Callbacks may be
321 * provided as functions or objects.
324 * @param callback* {Function|Object} 0..n callbacks
325 * @return {AsyncQueue} the AsyncQueue instance
329 this.fire('add', { callbacks: Y.Array(arguments,0,true) });
335 * Default functionality for the "add" event. Adds the callbacks
336 * in the event facade to the queue. Callbacks successfully added to the
337 * queue are present in the event's <code>added</code> property in the
341 * @param e {Event} the event object
344 _defAddFn : function(e) {
348 Y.Array.each(e.callbacks, function (c) {
359 * Pause the execution of the queue after the execution of the current
360 * callback completes. If called from code outside of a queued callback,
361 * clears the timeout for the pending callback. Paused queue can be
362 * restarted with q.run()
365 * @return {AsyncQueue} the AsyncQueue instance
369 if (isObject(this._running)) {
370 this._running.cancel();
373 this._running = false;
379 * Stop and clear the queue after the current execution of the
380 * current callback completes.
383 * @return {AsyncQueue} the AsyncQueue instance
393 * Returns the current index of a callback. Pass in either the id or
394 * callback function from getCallback.
397 * @param callback {String|Function} the callback or its specified id
398 * @return {Number} index of the callback or -1 if not found
400 indexOf : function (callback) {
401 var i = 0, len = this._q.length, c;
403 for (; i < len; ++i) {
405 if (c === callback || c.id === callback) {
414 * Retrieve a callback by its id. Useful to modify the configuration
415 * while the queue is running.
417 * @method getCallback
418 * @param id {String} the id assigned to the callback
419 * @return {Object} the callback object
421 getCallback : function (id) {
422 var i = this.indexOf(id);
424 return (i > -1) ? this._q[i] : null;
428 * Promotes the named callback to the top of the queue. If a callback is
429 * currently executing or looping (via until or iterations), the promotion
430 * is scheduled to occur after the current callback has completed.
433 * @param callback {String|Object} the callback object or a callback's id
434 * @return {AsyncQueue} the AsyncQueue instance
437 promote : function (callback) {
438 var payload = { callback : callback },e;
440 if (this.isRunning()) {
441 e = this.after(SHIFT, function () {
442 this.fire(PROMOTE, payload);
446 this.fire(PROMOTE, payload);
453 * <p>Default functionality for the "promote" event. Promotes the
454 * named callback to the head of the queue.</p>
456 * <p>The event object will contain a property "callback", which
457 * holds the id of a callback or the callback object itself.</p>
459 * @method _defPromoteFn
460 * @param e {Event} the custom event
463 _defPromoteFn : function (e) {
464 var i = this.indexOf(e.callback),
465 promoted = (i > -1) ? this._q.splice(i,1)[0] : null;
467 e.promoted = promoted;
470 this._q.unshift(promoted);
475 * Removes the callback from the queue. If the queue is active, the
476 * removal is scheduled to occur after the current callback has completed.
479 * @param callback {String|Object} the callback object or a callback's id
480 * @return {AsyncQueue} the AsyncQueue instance
483 remove : function (callback) {
484 var payload = { callback : callback },e;
486 // Can't return the removed callback because of the deferral until
487 // current callback is complete
488 if (this.isRunning()) {
489 e = this.after(SHIFT, function () {
490 this.fire(REMOVE, payload);
494 this.fire(REMOVE, payload);
501 * <p>Default functionality for the "remove" event. Removes the
502 * callback from the queue.</p>
504 * <p>The event object will contain a property "callback", which
505 * holds the id of a callback or the callback object itself.</p>
507 * @method _defRemoveFn
508 * @param e {Event} the custom event
511 _defRemoveFn : function (e) {
512 var i = this.indexOf(e.callback);
514 e.removed = (i > -1) ? this._q.splice(i,1)[0] : null;
518 * Returns the number of callbacks in the queue.
524 // next() flushes callbacks that have met their until() criteria and
525 // therefore shouldn't count since they wouldn't execute anyway.
526 if (!this.isRunning()) {
530 return this._q.length;
536 }, '3.0.0' ,{requires:['event-custom']});