views:

39

answers:

1

I am attempting to implement an asynchronous method queue in Javascript as seen in this blog post

Here's what I have so far:

function Queue() {
  this._methods = [];
  this._response = null;
  this._flushed = false;
}

(function(Q){

  Q.add = function (fn) {
    if (this._flushed) fn(this._response);
    else this._methods.push(fn);
  }

  Q.flush = function (response) {
    if (this._flushed) return;
    this._response = response;
    while (this._methods[0]) {
      this._methods.shift()(response);
    }
    this._flushed = true;
  }

})(Queue.prototype);

I can't seem to get it to work as advertised, although the code looks correct to me. When I call the flush function I get this._methods is undefined on the line while (this._methods[0]) {.

+2  A: 

How are you using it? If you're doing:

var q = new Queue();
q.flush("foo");

...you shouldn't be getting that error, and I'm not: http://jsbin.com/iduji3

T.J. Crowder
Yeah, I'm using it as a constructor. That's what's so weird.
Adam Lassek
Okay, looks like there was a scoping problem with the way I was using Queue#flush as a callback. It is working okay.
Adam Lassek
@Adam: Ah, if you were using it as a *callback*, your problem would be that `this` won't be what you're expecting in the callback. Two blog posts on this: [You must remember this](http://blog.niftysnippets.org/2008/04/you-must-remember-this.html) and [Mythical Methods](http://blog.niftysnippets.org/2008/03/mythical-methods.html) The second one is probably more on-target for what you're trying to do.
T.J. Crowder
@T.J. Yeah, I was inadvertently passing the function into a different scope. Dumb mistake. Moral: probably shouldn't have been coding at 3am. Calling queue.flush from within an anonymous function works fine.
Adam Lassek