0

I am trying to understand some code used to make a Node.js dispatcher but I can't understand one line. Maybe my JavaScript gap . . . I commented the code with my doubts.

var HttpDispatcher = function() {
  this.listeners = { get: [ ], post: [ ] };
}

HttpDispatcher.prototype.on = function(method, url, cb) {
  this.listeners[method].push({
    cb: cb,
    url: url
  });
}

HttpDispatcher.prototype.onGet = function(url, cb) {
  this.on('get', url, cb);
}

HttpDispatcher.prototype.onPost = function(url, cb) {
  this.on('post', url, cb);
}

HttpDispatcher.prototype.dispatch = function(req, res) {
  var parsedUrl = require('url').parse(req.url, true);
  var method = req.method.toLowerCase();
  this.listener[method][parsedUrl.pathname](req, res); // i don't understand this line
}

Why do we refer to this.listener as a bidimensional array? We defined listeners like an array of object! and why do we pass parameters?

1 Answer 1

1

It's not a bidimensional array, its bracket notation being used to access a nested property of an object.

this.listener[method][parsedUrl.pathname](req, res)
|-------------------||------------------||--------|
 ^object property of  ^nested function    ^ invocation of the function 
  the listener object  of the listener
  where the property   object where the
  key is the method    property key is
                       the path name

Properties of nested objects can be accessed by chaining dot and/or bracket references together. The following are all equivalent:

object.baz.foo.bar;
object["baz"]["foo"]["bar"];
object["baz"].foo["bar"];

Check this for more details.

Sign up to request clarification or add additional context in comments.

5 Comments

I can understand that with this.listeners['get'] we can access get array but in get array we have two properties
yes that's right, properties of nested objects can be accessed by chaining brackets together - if that's what you mean?
So here this.listener[method][parsedUrl.pathname](req, res); we access only to one property?
i've updated my explanation to make it clearer - it only accesses one function, so it can call it, but it uses 2 bracket references to reach it because its nested within the listener object
are we accessing to "cb" property or "url" property, inside listeners object?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.