获取一个asynchronous父函数的参数
我有这个:
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
传递callback没有path的文件名。 所以我希望它得到父函数参数_file
。 我以为我可以使用.call
,但如何在callback中做到这一点?
有很多的可能性,一个是使用Function.prototype.bind
,如果你不需要在callback中访问原来的this value
:
fs.watch( _file, change.bind({_file: _file});
这样你可以像访问_file
一样
this._file;
在你的callback方法中。
谨慎的一句话:请注意,您在callback方法中使用另一个匿名函数来callbackfiles.clients
。 this
没有引用相同的值。 所以如果你想访问我们新近通过的this
引用,你需要调用另一个.bind()
调用,或者只是在本地variables中存储一个外部引用。
- 我如何使用Bluebirderror handling程序?
- Node.js Docker镜像环境variables
- 如何让所有控制器都可以使用Q等库?
- 以RFC 2822格式parsingdatestring(在HTTP头字段“last-modified”中find)
- 使用VSCode在浏览器中debugging简单的Typescript应用程序
- 是否有可能为node.js中的模块variables定义一个设置函数
- 如何让CORS与Node.js(不使用Express)
- 通过使用Angularjs Expressjs Node和MEAN.js的POST方法将数组传递给$ resource
- 函数名可以在node.js中configuration吗?