Posterous theme by Cory Watilo

Async Method Queue Chaining (Dustin Diaz)

See Diaz’s article.

Head over to remy sharp’s JS Bin and play.

var Queue = function () {
  if (!(this instanceof arguments.callee)) {
      return new arguments.callee();
  }
  this._methods = [];
  this._response = null;
  this._flushed = false;
}

Queue.prototype = {
  add: function(fn) {
    (this._flushed) ?
      fn(this._response) :
      this._methods.push(fn);
  },
  flush: function(resp) {
    (this._flushed) && (return);
    this._response = resp;
    this._flushed = true;
    while (this._methods[0]) {
      this._methods.shift()(resp);
    }
  }
};