Dean
Dean

Reputation: 6950

Javascript - how to reference a callback from string/object

This code isn't working since it seems I declared an object with attributes. How to have it working and reference the callback from the string/object I pass?

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

HttpDispatcher.prototype.on = function(method, url, cb) {

  this.listeners[method].push({
    cb: cb,
    url: url 
  }); 
}

var obj = new HttpDispatcher();
obj.on("get", "page1", function() {document.write("hello");});

document.write(obj.listeners["get"]["page1"]()); // won't work for "page1"

Upvotes: 0

Views: 97

Answers (1)

Jonathan M
Jonathan M

Reputation: 17451

Perhaps you mean to do this:

HttpDispatcher.prototype.on = function(method, url, cb) {

  this.listeners[method][url]=cb;
}

This would allow you to call it as you did:

document.write(obj.listeners["get"]["page1"]());

Your current code is pushing into an array an element containing an object that has both the callback and url in it.

Upvotes: 3

Related Questions