Permalink
Browse files

Maintain 'this' throughout the layers.

  • Loading branch information...
1 parent f49abf6 commit 2f5005b237cf5925629d877893ebaabae53fedea @TooTallNate committed Feb 16, 2011
Showing with 5 additions and 4 deletions.
  1. +5 −4 stack.js
View
@@ -4,13 +4,14 @@ function Stack(/*layers*/) {
Array.prototype.slice.call(arguments).reverse().forEach(function (layer) {
var child = handle;
handle = function (req, res) {
+ var self = this;
try {
- layer(req, res, function (err) {
- if (err) { return error(req, res, err); }
- child(req, res);
+ layer.call(this, req, res, function (err) {
+ if (err) { return error.call(self, req, res, err); }
+ child.call(self, req, res);
});
} catch (err) {
- error(req, res, err);
+ error.call(this, req, res, err);
}
};
});

5 comments on commit 2f5005b

I never intended for this to be specified as anything special. Isn't there a performance hit for using .call? Do you really need this functionality? It was never part of the middleware interface I designed.

Not saying it's a bad idea, just not something I ever intended.

Owner

TooTallNate replied Feb 23, 2011

I don't really need the functionality, I just thought that these should do the same thing:

function layer(req, res) {
  console.log(this);
}

http.createServer(layer);
// and
http.createServer(stack(layer));

But you're right, mostly you don't need this in your connection/request callback, and this might be more appropriate for a stack++ or something, like you're suggesting. I'll probably do that, so don't bother with pulling these.

Is the value of this specified for normal http handlers? If so, then I can see a good reason to follow that pattern. I just wasn't aware and thought it was unspecified.

Owner

TooTallNate replied Feb 23, 2011

It goes up to EventEmitters. When an event emitter emits an event, this in the handler function is the EventEmitter instance. In the case of http.Server, when request is emitted, this is the http.Server instance.

Please sign in to comment.