Reputation: 2210
i've this code:
function myfunction(url_parts){
fs.unlink(__dirname + '/temp/' + url_parts + '.pdf', function(err){
if (err) console.log(err);
console.log('unlink ok');
});
}
var url_parts= 'filename'
req.on("close", myfunction(url_parts));
I get error "listener must be a function". But myfunction is a function :D what's wrong?? I don't get this error if i don't pass any param to myfunction, but i need to pass url_parts. I can't use anonymous function because i need to call removeListener method in another part of the code.
req.removeListener('close', myfunction);
Upvotes: 2
Views: 1500
Reputation: 32118
AFAIK anything that uses events in Node.js are extended on EventEmitter.
You could try using an anonymous function to add the listener, and to remove it:
req.removeAllListeners('close');
Upvotes: 0
Reputation: 2652
You should use the bind function (Assigned to the Function.prototype). Your code will become (Changing the last line only)
function myfunction(url_parts){
fs.unlink(__dirname + '/temp/' + url_parts + '.pdf', function(err){
if (err) console.log(err);
console.log('unlink ok');
});
}
var url_parts= 'filename'
req.on("close", myfunction.bind(null, url_parts));
The bind function allows you to create a new function which will pass the arguments you define when calling bind to the function everytime it is called in the future.
To remove the event later, you should remove the result of the bind call, not the original function.
Upvotes: 3