Let's take stdin.on
as an example. Callbacks to stdin.on
stack, so if I write (in CoffeeScript)
stdin = process.openStdin()
stdin.setEncoding 'utf8'
stdin.on 'data', (input) -> console.log 'One'
stdin.on 'data', (input) -> console.log 'Two'
then every time I hit return at the prompt, I get
One
Two
My question is, is there any way to remove/replace a callback once bound? Or is the only approach to bind a proxy callback and manage state myself?
The EventEmitter is a module that facilitates communication/interaction between objects in Node. EventEmitter is at the core of Node asynchronous event-driven architecture. Many of Node's built-in modules inherit from EventEmitter including prominent frameworks like Express.
The event loop is what allows Node. js to perform non-blocking I/O operations — despite the fact that JavaScript is single-threaded — by offloading operations to the system kernel whenever possible. Since most modern kernels are multi-threaded, they can handle multiple operations executing in the background.
libuv is a multi-platform C library that provides support for asynchronous I/O based on event loops. It supports epoll(4) , kqueue(2) , Windows IOCP, and Solaris event ports. It is primarily designed for use in Node. js but it is also used by other software projects.
You can use removeListener(eventType, callback)
to remove an event, which should work with all kinds of emitters.
Example from the API docs:
var callback = function(stream) {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
So you need to have a variable that holds a reference to the callback, because obviously, it's otherwise impossible to tell which callback you want to have removed.
EDIT
Should be someone like this in CS:
stdin = process.openStdin()
stdin.setEncoding 'utf8'
logger = (input) -> console.log 'One'
stdin.on 'data', logger
stdin.removeListener 'data', logger
stdin.on 'data', (input) -> console.log 'Two'
See: http://nodejs.org/docs/latest/api/events.html#emitter.removeListener
Or you can use:
stdin.once
instead of stdin.on
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With