Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

arguments to callback not being passed (Node.js)

arguments to callback not being passed (Node.js)

Problem

In the code below, I am trying to pass the Argument "test" to the callback. The good news is that the callback is indeed being called; however, the string "I see undefined" is being printed instead of "I see test".

var MyObject = function(){
}

MyObject.prototype.b = function(data){
   console.log("I see " + data);
}

a = function(callback){
   callback("test");
}

var it = new MyObject();
a(function(){it.b()});

I have a hunch it has something to do with the closure, since I see the string "I see test" printed if I call it.b("test") directly. Why isn't the function receiving the argument properly?

Problem courtesy of: Michael D. Moffitt

Solution

You are calling it.b() with no arguments, so it should be no surprise that there are no arguments when you get in the b() method. If you want an argument to appear for it.b(), you have to declare it in your callback so you can then pass it to it.b(arg).

a(function(arg){
    it.b(arg)
});

Or, you could pass all arguments from the callback:

a(function(){
    it.b.apply(it, arguments)
});

Or, you could use .bind().

a(it.b.bind(it));
Solution courtesy of: jfriend00

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

arguments to callback not being passed (Node.js)

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×