Here are three options:
- Use
.bind()
to automatically prepend arguments to the callback (technically this creates a new function stub that adds that argument).
- Manually create your own wrapper function that adds the argument.
- Create a new version of
.on()
that accepts your level
argument and adds it to the callback before calling the callback.
Using .bind()
If you are not relying on a value of this
being passed into your callback, then you can use .bind()
to create a new function that will have the level
argument automatically prepended to the callback arguments.
// 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));
}
Manually Creating Your Own Wrapper Function
Or, you can create your own wrapper function that returns a function, but captures the parameter you wanted:
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));
}
Creating a Replacement for .on()
Or, you can create a wrapper for monitor.on()
that captures your level value:
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);
}