The events
module supports events. Use require('events')
to access this module.
An instance of EventEmitter
class will emits events. If you need to define a class emitting events, you can defined a class by extending from EventEmitter
.
var EventEmitter = require('events').EventEmitter;class MyEmitter extends EventEmitter {}var myEmitter = new MyEmitter();myEmitter.on('event', () => {console.log('event occurred!');});myEmitter.emit('event');
eventName
{string}
The name of event
listener
{function}
The callback function
Add the listener
function to the end of the listener array for the event named eventName
.
server.addListener('connect', function () { // equivalent to server.onconsole.log('server connected');});
eventName
{string}
The name of event
...args
{any}
Arguments to be passed to the listener functions.
Synchronously calls each of the listeners registered for the event named eventName
, in the order they were registered, passing the supplied arguments to each.
server.on('data', function (data) {console.log(data); // "data received"})var data = "data recived"server.emit('data', data);
eventName
{string}
The name of event.
listener
{function}
The callback function.
Alias for emitter.addListener(eventName, listener)
.
server.on('connect', function () {console.log('server connected');});
eventName
{string}
The name of event.
listener
{function}
The callback function.
Add one-time listener
for the event named eventName
. When the event is triggered, the listener
function is called and then removed from the listener array of the event.
server.once('connect', function () {console.log('connected');})server.emit('connect'); // 'connected' printedserver.emit('connect'); // nothing printed
eventName
{string}
The name of event.
listener
{function}
The callback function.
Remove the listener
function from the listener array of the event name eventName
.
function connectListener () {console.log('connected');}server.addListener('connect', connectListener); // eq to server.onserver.emit('connect'); // 'connected' printedserver.removeListener('connect' connectListener); // eq to server.offserver.emit('connect'); // nothing printed
eventName
{string}
Remove all listeners of the event named eventName
.
eventName
{string}
The name of event.
listener
{function}
The callback function
Alias for emitter.removeListener(eventName, listener)
.
eventName
{string}
The name of event.
Returns: {Array<Function>}
Return all listeners of the given event.
eventName
{string}
The name of event.
Returns: {number}
Return the number of listeners of the given event.