src/cm/media/js/lib/yui/yui_3.0.0b1/build/queue/queue-run.js
changeset 0 40c8f766c9b8
equal deleted inserted replaced
-1:000000000000 0:40c8f766c9b8
       
     1 /*
       
     2 Copyright (c) 2009, Yahoo! Inc. All rights reserved.
       
     3 Code licensed under the BSD License:
       
     4 http://developer.yahoo.net/yui/license.txt
       
     5 version: 3.0.0b1
       
     6 build: 1163
       
     7 */
       
     8 YUI.add('queue-run', function(Y) {
       
     9 
       
    10 /**
       
    11  * <p>Adds a new class AsyncQueue that is restricted to function callbacks, but
       
    12  * includes a host of additional features, including events, callback
       
    13  * iterations, and a run() method that can execute queued callbacks in order,
       
    14  * even across configured timeouts.</p>
       
    15  *
       
    16  * @module queue
       
    17  * @submodule queue-run
       
    18  */
       
    19 
       
    20 /**
       
    21  * <p>A specialized queue class that supports scheduling callbacks to execute
       
    22  * sequentially, iteratively, even asynchronously.</p>
       
    23  *
       
    24  * <p>Callbacks can be function refs or objects with the following keys.  Only
       
    25  * the <code>fn</code> key is required.</p>
       
    26  *
       
    27  * <ul>
       
    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>
       
    41  * </ul>
       
    42  *
       
    43  * @class AsyncQueue
       
    44  * @extends EventTarget
       
    45  * @constructor
       
    46  * @param callback* {Function|Object} 0..n callbacks to seed the queue
       
    47  */
       
    48 Y.AsyncQueue = function() {
       
    49     this._init();
       
    50     this.add.apply(this, arguments);
       
    51 };
       
    52 
       
    53 var Queue   = Y.AsyncQueue,
       
    54     EXECUTE = 'execute',
       
    55     SHIFT   = 'shift',
       
    56     PROMOTE = 'promote',
       
    57     REMOVE  = 'remove',
       
    58 
       
    59     isObject   = Y.Lang.isObject,
       
    60     isFunction = Y.Lang.isFunction;
       
    61 
       
    62 /**
       
    63  * <p>Static default values used to populate callback configuration properties.
       
    64  * Preconfigured defaults include:</p>
       
    65  *
       
    66  * <ul>
       
    67  *  <li><code>autoContinue</code>: <code>true</code></li>
       
    68  *  <li><code>iterations</code>: 1</li>
       
    69  *  <li><code>timeout</code>: -1 (synchronous operation)</li>
       
    70  *  <li><code>until</code>: (function to run until iterations &lt;= 0)</li>
       
    71  * </ul>
       
    72  *
       
    73  * @property AsyncQueue.defaults
       
    74  * @type {Object}
       
    75  * @static
       
    76  */
       
    77 Queue.defaults = Y.mix({
       
    78     autoContinue : true,
       
    79     iterations   : 1,
       
    80     timeout      : -1,
       
    81     until        : function () {
       
    82         this.iterations |= 0;
       
    83         return this.iterations <= 0;
       
    84     }
       
    85 }, Y.config.queueDefaults || {});
       
    86 
       
    87 Y.extend(Queue, Y.EventTarget, {
       
    88     /**
       
    89      * Used to indicate the queue is currently executing a callback.
       
    90      *
       
    91      * @property _running
       
    92      * @type {Boolean|Object} true for synchronous callback execution, the
       
    93      *                        return handle from Y.later for async callbacks
       
    94      * @protected
       
    95      */
       
    96     _running : false,
       
    97 
       
    98     /**
       
    99      * Initializes the AsyncQueue instance properties and events.
       
   100      *
       
   101      * @method _init
       
   102      * @protected
       
   103      */
       
   104     _init : function () {
       
   105         Y.EventTarget.call(this, { emitFacade: true });
       
   106 
       
   107         this._q = [];
       
   108 
       
   109         /** 
       
   110          * Callback defaults for this instance.  Static defaults that are not
       
   111          * overridden are also included.
       
   112          *
       
   113          * @property defaults
       
   114          * @type {Object}
       
   115          */
       
   116         this.defaults = {};
       
   117 
       
   118         this._initEvents();
       
   119     },
       
   120 
       
   121     /**
       
   122      * Initializes the instance events.
       
   123      *
       
   124      * @method _initEvents
       
   125      * @protected
       
   126      */
       
   127     _initEvents : function () {
       
   128         /*
       
   129         this.publish({
       
   130             'execute' : { defaultFn : this._defExecFn },
       
   131             'shift'   : { defaultFn : this._defShiftFn },
       
   132             'add'     : { defaultFn : this._defAddFn },
       
   133             'promote' : { defaultFn : this._defPromoteFn },
       
   134             'remove'  : { defaultFn : this._defRemoveFn }
       
   135         });
       
   136         */
       
   137         this.publish('execute' , { defaultFn : this._defExecFn, emitFacade: true });
       
   138         this.publish('shift'   , { defaultFn : this._defShiftFn, emitFacade: true });
       
   139         this.publish('add'     , { defaultFn : this._defAddFn, emitFacade: true });
       
   140         this.publish('promote' , { defaultFn : this._defPromoteFn, emitFacade: true });
       
   141         this.publish('remove'  , { defaultFn : this._defRemoveFn, emitFacade: true });
       
   142     },
       
   143 
       
   144     /**
       
   145      * Returns the next callback needing execution.  If a callback is
       
   146      * configured to repeat via iterations or until, it will be returned until
       
   147      * the completion criteria is met.
       
   148      *
       
   149      * When the queue is empty, null is returned.
       
   150      *
       
   151      * @method next
       
   152      * @return {Function} the callback to execute
       
   153      */
       
   154     next : function () {
       
   155         var callback;
       
   156 
       
   157         while (this._q.length) {
       
   158             callback = this._q[0] = this._prepare(this._q[0]);
       
   159             if (callback && callback.until()) {
       
   160                 this.fire(SHIFT, { callback: callback });
       
   161                 callback = null;
       
   162             } else {
       
   163                 break;
       
   164             }
       
   165         }
       
   166 
       
   167         return callback || null;
       
   168     },
       
   169 
       
   170     /**
       
   171      * Default functionality for the &quot;shift&quot; event.  Shifts the
       
   172      * callback stored in the event object's <em>callback</em> property from
       
   173      * the queue if it is the first item.
       
   174      *
       
   175      * @method _defShiftFn
       
   176      * @param e {Event} The event object
       
   177      * @protected
       
   178      */
       
   179     _defShiftFn : function (e) {
       
   180         if (this.indexOf(e.callback) === 0) {
       
   181             this._q.shift();
       
   182         }
       
   183     },
       
   184 
       
   185     /**
       
   186      * Creates a wrapper function to execute the callback using the aggregated 
       
   187      * configuration generated by combining the static AsyncQueue.defaults, the
       
   188      * instance defaults, and the specified callback settings.
       
   189      *
       
   190      * The wrapper function is decorated with the callback configuration as
       
   191      * properties for runtime modification.
       
   192      *
       
   193      * @method _prepare
       
   194      * @param callback {Object|Function} the raw callback
       
   195      * @return {Function} a decorated function wrapper to execute the callback
       
   196      * @protected
       
   197      */
       
   198     _prepare: function (callback) {
       
   199         if (isFunction(callback) && callback._prepared) {
       
   200             return callback;
       
   201         }
       
   202 
       
   203         var config = Y.merge(
       
   204             Queue.defaults,
       
   205             { context : this, args: [], _prepared: true },
       
   206             this.defaults,
       
   207             (isFunction(callback) ? { fn: callback } : callback)),
       
   208             
       
   209             wrapper = Y.bind(function () {
       
   210                 if (!wrapper._running) {
       
   211                     wrapper.iterations--;
       
   212                 }
       
   213                 if (isFunction(wrapper.fn)) {
       
   214                     wrapper.fn.apply(wrapper.context || Y,
       
   215                                      Y.Array(wrapper.args));
       
   216                 }
       
   217             }, this);
       
   218             
       
   219         return Y.mix(wrapper, config);
       
   220     },
       
   221 
       
   222     /**
       
   223      * Sets the queue in motion.  All queued callbacks will be executed in
       
   224      * order unless pause() or stop() is called or if one of the callbacks is
       
   225      * configured with autoContinue: false.
       
   226      *
       
   227      * @method run
       
   228      * @return {AsyncQueue} the AsyncQueue instance
       
   229      * @chainable
       
   230      */
       
   231     run : function () {
       
   232         var callback,
       
   233             cont = true;
       
   234 
       
   235         for (callback = this.next();
       
   236             cont && callback && !this.isRunning();
       
   237             callback = this.next())
       
   238         {
       
   239             cont = (callback.timeout < 0) ?
       
   240                 this._execute(callback) :
       
   241                 this._schedule(callback);
       
   242         }
       
   243 
       
   244         if (!callback) {
       
   245             /**
       
   246              * Event fired after the last queued callback is executed.
       
   247              * @event complete
       
   248              */
       
   249             this.fire('complete');
       
   250         }
       
   251 
       
   252         return this;
       
   253     },
       
   254 
       
   255     /**
       
   256      * Handles the execution of callbacks. Returns a boolean indicating
       
   257      * whether it is appropriate to continue running.
       
   258      *
       
   259      * @method _execute
       
   260      * @param callback {Object} the callback object to execute
       
   261      * @return {Boolean} whether the run loop should continue
       
   262      * @protected
       
   263      */
       
   264     _execute : function (callback) {
       
   265         this._running = callback._running = true;
       
   266 
       
   267         callback.iterations--;
       
   268         this.fire(EXECUTE, { callback: callback });
       
   269 
       
   270         var cont = this._running && callback.autoContinue;
       
   271 
       
   272         this._running = callback._running = false;
       
   273 
       
   274         return cont;
       
   275     },
       
   276 
       
   277     /**
       
   278      * Schedules the execution of asynchronous callbacks.
       
   279      *
       
   280      * @method _schedule
       
   281      * @param callback {Object} the callback object to execute
       
   282      * @return {Boolean} whether the run loop should continue
       
   283      * @protected
       
   284      */
       
   285     _schedule : function (callback) {
       
   286         this._running = Y.later(callback.timeout, this, function () {
       
   287             if (this._execute(callback)) {
       
   288                 this.run();
       
   289             }
       
   290         });
       
   291 
       
   292         return false;
       
   293     },
       
   294 
       
   295     /**
       
   296      * Determines if the queue is waiting for a callback to complete execution.
       
   297      *
       
   298      * @method isRunning
       
   299      * @return {Boolean} true if queue is waiting for a 
       
   300      *                   from any initiated transactions
       
   301      */
       
   302     isRunning : function () {
       
   303         return !!this._running;
       
   304     },
       
   305 
       
   306     /**
       
   307      * Default functionality for the &quot;execute&quot; event.  Executes the
       
   308      * callback function
       
   309      *
       
   310      * @method _defExecFn
       
   311      * @param e {Event} the event object
       
   312      * @protected
       
   313      */
       
   314     _defExecFn : function (e) {
       
   315         e.callback();
       
   316     },
       
   317 
       
   318     /**
       
   319      * Add any number of callbacks to the end of the queue. Callbacks may be
       
   320      * provided as functions or objects.
       
   321      *
       
   322      * @method add
       
   323      * @param callback* {Function|Object} 0..n callbacks
       
   324      * @return {AsyncQueue} the AsyncQueue instance
       
   325      * @chainable
       
   326      */
       
   327     add : function () {
       
   328         this.fire('add', { callbacks: Y.Array(arguments,0,true) });
       
   329 
       
   330         return this;
       
   331     },
       
   332 
       
   333     /**
       
   334      * Default functionality for the &quot;add&quot; event.  Adds the callbacks
       
   335      * in the event facade to the queue. Callbacks successfully added to the
       
   336      * queue are present in the event's <code>added</code> property in the
       
   337      * after phase.
       
   338      *
       
   339      * @method _defAddFn
       
   340      * @param e {Event} the event object
       
   341      * @protected
       
   342      */
       
   343     _defAddFn : function(e) {
       
   344         var _q = this._q,
       
   345             added = [];
       
   346 
       
   347         Y.Array.each(e.callbacks, function (c) {
       
   348             if (isObject(c)) {
       
   349                 _q.push(c);
       
   350                 added.push(c);
       
   351             }
       
   352         });
       
   353 
       
   354         e.added = added;
       
   355     },
       
   356 
       
   357     /**
       
   358      * Pause the execution of the queue after the execution of the current
       
   359      * callback completes.  If called from code outside of a queued callback,
       
   360      * clears the timeout for the pending callback. Paused queue can be
       
   361      * restarted with q.run()
       
   362      *
       
   363      * @method pause
       
   364      * @return {AsyncQueue} the AsyncQueue instance
       
   365      * @chainable
       
   366      */
       
   367     pause: function () {
       
   368         if (isObject(this._running)) {
       
   369             this._running.cancel();
       
   370         }
       
   371 
       
   372         this._running = false;
       
   373 
       
   374         return this;
       
   375     },
       
   376 
       
   377     /**
       
   378      * Stop and clear the queue after the current execution of the
       
   379      * current callback completes.
       
   380      *
       
   381      * @method stop
       
   382      * @return {AsyncQueue} the AsyncQueue instance
       
   383      * @chainable
       
   384      */
       
   385     stop : function () { 
       
   386         this._q = [];
       
   387 
       
   388         return this.pause();
       
   389     },
       
   390 
       
   391     /** 
       
   392      * Returns the current index of a callback.  Pass in either the id or
       
   393      * callback function from getCallback.
       
   394      *
       
   395      * @method indexOf
       
   396      * @param callback {String|Function} the callback or its specified id
       
   397      * @return {Number} index of the callback or -1 if not found
       
   398      */
       
   399     indexOf : function (callback) {
       
   400         var i = 0, len = this._q.length, c;
       
   401 
       
   402         for (; i < len; ++i) {
       
   403             c = this._q[i];
       
   404             if (c === callback || c.id === callback) {
       
   405                 return i;
       
   406             }
       
   407         }
       
   408 
       
   409         return -1;
       
   410     },
       
   411 
       
   412     /**
       
   413      * Retrieve a callback by its id.  Useful to modify the configuration
       
   414      * while the queue is running.
       
   415      *
       
   416      * @method getCallback
       
   417      * @param id {String} the id assigned to the callback
       
   418      * @return {Object} the callback object
       
   419      */
       
   420     getCallback : function (id) {
       
   421         var i = this.indexOf(id);
       
   422 
       
   423         return (i > -1) ? this._q[i] : null;
       
   424     },
       
   425 
       
   426     /**
       
   427      * Promotes the named callback to the top of the queue. If a callback is
       
   428      * currently executing or looping (via until or iterations), the promotion
       
   429      * is scheduled to occur after the current callback has completed.
       
   430      *
       
   431      * @method promote
       
   432      * @param callback {String|Object} the callback object or a callback's id
       
   433      * @return {AsyncQueue} the AsyncQueue instance
       
   434      * @chainable
       
   435      */
       
   436     promote : function (callback) {
       
   437         var payload = { callback : callback },e;
       
   438 
       
   439         if (this.isRunning()) {
       
   440             e = this.after(SHIFT, function () {
       
   441                     this.fire(PROMOTE, payload);
       
   442                     e.detach();
       
   443                 }, this);
       
   444         } else {
       
   445             this.fire(PROMOTE, payload);
       
   446         }
       
   447 
       
   448         return this;
       
   449     },
       
   450 
       
   451     /**
       
   452      * <p>Default functionality for the &quot;promote&quot; event.  Promotes the
       
   453      * named callback to the head of the queue.</p>
       
   454      *
       
   455      * <p>The event object will contain a property &quot;callback&quot;, which
       
   456      * holds the id of a callback or the callback object itself.</p>
       
   457      *
       
   458      * @method _defPromoteFn
       
   459      * @param e {Event} the custom event
       
   460      * @protected
       
   461      */
       
   462     _defPromoteFn : function (e) {
       
   463         var i = this.indexOf(e.callback),
       
   464             promoted = (i > -1) ? this._q.splice(i,1)[0] : null;
       
   465 
       
   466         e.promoted = promoted;
       
   467 
       
   468         if (promoted) {
       
   469             this._q.unshift(promoted);
       
   470         }
       
   471     },
       
   472 
       
   473     /**
       
   474      * Removes the callback from the queue.  If the queue is active, the
       
   475      * removal is scheduled to occur after the current callback has completed.
       
   476      *
       
   477      * @method remove
       
   478      * @param callback {String|Object} the callback object or a callback's id
       
   479      * @return {AsyncQueue} the AsyncQueue instance
       
   480      * @chainable
       
   481      */
       
   482     remove : function (callback) {
       
   483         var payload = { callback : callback },e;
       
   484 
       
   485         // Can't return the removed callback because of the deferral until
       
   486         // current callback is complete
       
   487         if (this.isRunning()) {
       
   488             e = this.after(SHIFT, function () {
       
   489                     this.fire(REMOVE, payload);
       
   490                     e.detach();
       
   491                 },this);
       
   492         } else {
       
   493             this.fire(REMOVE, payload);
       
   494         }
       
   495 
       
   496         return this;
       
   497     },
       
   498 
       
   499     /**
       
   500      * <p>Default functionality for the &quot;remove&quot; event.  Removes the
       
   501      * callback from the queue.</p>
       
   502      *
       
   503      * <p>The event object will contain a property &quot;callback&quot;, which
       
   504      * holds the id of a callback or the callback object itself.</p>
       
   505      *
       
   506      * @method _defRemoveFn
       
   507      * @param e {Event} the custom event
       
   508      * @protected
       
   509      */
       
   510     _defRemoveFn : function (e) {
       
   511         var i = this.indexOf(e.callback);
       
   512 
       
   513         e.removed = (i > -1) ? this._q.splice(i,1)[0] : null;
       
   514     },
       
   515 
       
   516     /**
       
   517      * Returns the number of callbacks in the queue.
       
   518      *
       
   519      * @method size
       
   520      * @return {Number}
       
   521      */
       
   522     size : function () {
       
   523         // next() flushes callbacks that have met their until() criteria and
       
   524         // therefore shouldn't count since they wouldn't execute anyway.
       
   525         if (!this.isRunning()) {
       
   526             this.next();
       
   527         }
       
   528 
       
   529         return this._q.length;
       
   530     }
       
   531 });
       
   532 
       
   533 
       
   534 
       
   535 }, '3.0.0b1' ,{requires:['queue-base','oop','event-custom']});