Wednesday, 30 May 2018

010 Node.js EventEmitter

EventEmitter class is used to raise and handle events. An objects  emit events but all  events  are instances of the EventEmitter class. When object emits  event ,event related functions  are called synchronously.
 

Example

const EventEmitter = require('events');

class objEmitter extends EventEmitter {}

const myEventEmitter = new objEmitter();
myEventEmitter .on('event', () => {
  console.log('an event fired!!');
});
myEventEmitter .emit('event');
 

Output :
an event fired!! 

Example Explain : 

The module 'events' included in a variable called 'EventEmitter' .Instance of 'EventEmitter' class created and assigned to 'myEventEmitter'.The eventEmitter.on() method is used to register listeners and eventEmitter.emit() method is used to fires the event.


Below are some method of EventEmitter Class
  • emitter.addListener(eventName, listener)
Attach listener function to listeners array for the event named eventName.
  • emitter.emit(eventName[, ...args])
Calls each of the listeners registered for the event named eventName
one by one.
  • emitter.eventNames()
Returns an array listing the events for which the emitter has registered listeners.
  • emitter.getMaxListeners()
Returns maximum listener value.
  • emitter.listenerCount(eventName)
Returns the number of listeners listening.
  • emitter.listeners(eventName)
Returns a copy of the array of listeners.
  • emitter.off(eventName, listener)
Deactivate the  listener from the listener array.
  • emitter.on(eventName, listener)
Attach listener function to the  listeners array for the event named eventName.By default, event listeners are invoked in a order , as they have are added.

  • emitter.once(eventName, listener)
Attach listener function for one-time.If triggered again , this listener is removed and then invoked.

  • emitter.prependListener(eventName, listener)
Attach the listener function to the beginning of the listeners array. 

  • emitter.prependOnceListener(eventName, listener)
Attach listener function for one-time at the begining of listeners array.

  • emitter.removeAllListeners([eventName])
Removes all listeners.
  • emitter.removeListener(eventName, listener)
Removes the specified listener from the listener array.


  • emitter.setMaxListeners(n)
Allows the limit to be modified for number of listeners



No comments:

Post a Comment

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...