How to manage events with node.js

 

With Node.js events library, it’s very easy to manage node.js events : you can emit or catch event, it’s as easy as pie. Demonstration…..


 

To do before reading

– know what node.js is (see blog post Comprendre node.js)
node.js installed (see blog post on Installer node.js sous Windows);
– know what javascript event is (see blog post javascript : créer des événements personnalisés custom event).

 

node.js EventEmitter object

node.js contains some library to build application. With events node.js library you can run or catch events.
For using, you need to create an EventEmitter object like this :

var eventEmitter = require('events').EventEmitter;

With this class, you can use some methods to listen or emit an event.

 

Emit an event with node.js

Just call emit method from eventEmitter object :

eventEmitter.emit(event, [arg1], [arg2], [...]);

The next example emit an event called « monEvenement » with some data (format json) :

eventEmitter.emit("monEvenement", {"donneeA":"1","donneeB":"2"});

 

Listen an node.js event

Just call on method from eventEmitter object. When the event is being caught, anonymous function in parameter will call.
It is the function in parameter that is listening event :

eventEmitter.on(event, function([arg1], [arg2], [...]) {});

Example of listener based on previous paragraph :

eventEmitter.on("monEvenement", function(data) {
  console.log(data.donneeA);
  console.log(data.donneeB);
});

 

Other node.js EventEmitter methods

EventEmitter once method take some parameters as EventEmitter on method : adds a one time listener for the event. This listener is invoked only the next time the event is fired, after which it is removed;
– method EventEmitter removeListener(event, listener) Remove a listener from the listener array for the specified event. Caution: changes array indices in the listener array behind the listener;
– method EventEmitter removeAllListeners(event) removes all listeners, or those of the specified event;
– method EventEmitter setMaxListeners(n) : by default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default which helps finding memory leaks. Obviously not all Emitters should be limited to 10. This function allows that to be increased. Set to zero for unlimited.

 

If you liked this post, share it.

 

Comments, improvement, idea : let me know. If this post has been helpful, make comments on your favorite social networks.

Source node.js Events

 

Posté dans node.jsTaggé eventemitter, node.js, node.js event  |  Laisser un commentaire

Répondre