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

Get an argument of an asynchronous parent function

Get an argument of an asynchronous parent function

Problem

I have this:

function change( event, file ) {
  console.log( "filename", file );
  //It should be '_file', not 'file'.
  files.clients( file, function( clientOfFile ) {
    console.log( "for client:", clientOfFile );
    io.sockets.socket( clientOfFile ).emit( "change" );
  } );
}

client.on( "watch", function( file ) {
   _file = base + file; //filename with path
   files.add( _file, client.id );
   fs.watch( _file, change );
} );

fs.watch passes to Callback a filename without path. So I want it to get parent Function argument _file. I thought I can use .call, but how to do it in callback?

Problem courtesy of: Hahi

Solution

Plenty of possiblitys, one is to use Function.prototype.bind, if you don't need to have access to the original this value within the callback:

fs.watch( _file, change.bind({_file: _file});

That way you can access _file like

this._file;

within your callback method.


One word of caution: Be aware that you are using another anonymous function in your callback method for the callback of files.clients. this does not reference the same value within there. So if you want to access our newly passed this reference there, you need to either invoke another .bind() call or just store an outer reference to this in a local variable.

Solution courtesy of: jAndy

Discussion

View additional discussion.



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

Share the post

Get an argument of an asynchronous parent function

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×