本文介绍了将附加参数传递给 Javascript 回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 Node.JS 应用程序中查看少量目录:

I need to watch a small number of directories in a Node.JS application:

function updated(event, filename){
    log("CHANGED	/share/channels/" + filename);
}
for(i in channels)
    fs.watch('share/channels/' + channels[i], {persistent: false}, updated);

问题是 fs.watch 只将文件名传递给回调函数,而不包括它所在的目录.是吗?

The problem is that fs.watch only passes the filename to the callback function, without including the directory it's in. Is there a way I can somehow pass in an extra parameter to the updated() function so it knows where the file is?

我想我正在寻找类似于 Python 的 functools.partial 的东西,如果有帮助的话.

I think I'm looking for something similar to Python's functools.partial, if that helps any.

推荐答案

您可以使用 Function.bind:

You can use Function.bind:

function updated(extraInformation, event, filename) {
    log("CHANGED	/share/channels/" + extraInformation + filename);
}

for(i in channels)
    fs.watch('share/channels/' + channels[i], {persistent: false},
              updated.bind(null, 'wherever/it/is/'));

这篇关于将附加参数传递给 Javascript 回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:55