我正在编写一个ping应用程序,它将每个ping记录到日志文件中。根据结果,我写了一个信息或错误条目。
这是ping函数:
function pingServer(item){
var monitor = new Monitor({
website: item.url,
interval: interval
});
monitor.on('up', writeInfo);
monitor.on('down', writeError);
}
我想要一个唯一的回调函数writeLog而不是writeInfo和writeError函数,但我不知道如何在该回调中传递一个参数。
所以而不是
function writeInfo(res){
logger.info(getVarLine(res));
}
function writeError(res){
logger.error(getVarLine(res));
}
我会有类似的东西:
function writeLog(res, level){
if (level=='info'){
logger.info(getVarLine(res));
} else {
logger.error(getVarLine(res));
}
}
答案 0 :(得分:3)
以下是三个选项:
.bind()
自动为回调添加参数(从技术上讲,这会创建一个添加该参数的新函数存根)。.on()
,接受您的level
参数,并在调用回调之前将其添加到回调中。.bind()
如果您不依赖于this
的值被传递回回调,那么您可以使用.bind()
创建一个新的函数,该函数将自动添加level
参数回调参数。
// note how the arguments had to be switched here so level was first to match
// up with how .bind() works
function writeLog(level, res){
if (level=='info'){
logger.info(getVarLine(res));
} else {
logger.error(getVarLine(res));
}
}
function pingServer(item){
var monitor = new Monitor({
website: item.url,
interval: interval
});
monitor.on('up', writeLog.bind(null, level));
monitor.on('down', writeLog.bind(null, level));
}
或者,您可以创建自己的包装函数来返回函数,但会捕获您想要的参数:
function writeLogCallback(level) {
return function(res) {
if (level=='info'){
logger.info(getVarLine(res));
} else {
logger.error(getVarLine(res));
}
}
}
function pingServer(item){
var monitor = new Monitor({
website: item.url,
interval: interval
});
monitor.on('up', writeLogCallback(level));
monitor.on('down', writeLogCallback(level));
}
.on()
或者,您可以为monitor.on()
创建一个捕获您的级别值的包装器:
Monitor.prototype.onWithLevel = function(event, level, callback) {
this.on(event, function(res) {
return callback(res, level);
});
}
function writeLog(res, level){
if (level=='info'){
logger.info(getVarLine(res));
} else {
logger.error(getVarLine(res));
}
}
function pingServer(item){
var monitor = new Monitor({
website: item.url,
interval: interval
});
monitor.onWithLevel('up', level, writeLog);
monitor.onWithLevel('down', level, writeLog);
}
答案 1 :(得分:0)
这是你如何实现你想要的(即将参数传递给回调):
monitor.on('up', writeLog('info'));
monitor.on('down', writeLog('error'));
// You pass the log level
function writeLog(level) {
// and you return a function that will be called
// with your data when the event is triggered
return function(res) {
if (level=='info'){
logger.info(getVarLine(res));
} else {
logger.error(getVarLine(res));
}
}
}