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?
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.