Node JS Add Emit Event Feature To JavaScript Function Object Example

Node js use event loop to process client request, sometimes you need to make your javascript object can emit event also. This example will show you how to enable your javascript function object with emit event functions.

1. Steps To Enable JS Object With Emit Event Function.

  1. Require node js events module.
    var events = require('events');
  2. Create a javascript function object.
    var Counter = function () {......}
  3. Create an instance of events.EventEmitter and set it as the prototype of above function object. This is something like create child class of EventEmitter in java.
    Counter.prototype = new events.EventEmitter();
  4. Then you can use EventEmitter’s addListener method to add a callback function as the listener to specified event. When you use EventEmitter’s emit method to emit addValue event, add_value_callback function will be invoked.
    counter.addListener('addValue', add_value_callback);
  5. You can also use EventEmitter’s removeListener method to remove registered listener from special event. After removed when you emit addValue event again, no function will be invoked.
    counter.removeListener('addValue', add_value_callback);

2. Add Emit Event Function To JavaScript Function Object Example.


// Require node js events module.
var events = require('events');

// Create a function object.
var Counter = function (initValue) {

    // addValue is a method of Counter object.
    this.addValue = function () {

        // Plus 1 to initValue.
        initValue = initValue + 1;

        // Emit addValue event to node js event loop. The second parameter is the new value.
        this.emit('addValue', initValue);

// Make an EventEmitter object in events module as Counter function object's prototype.
// Then all Counter instance can emit event to node js event loop.
Counter.prototype = new events.EventEmitter();

// Create a new Counter object with initial value 1.
var counter = new Counter(1);

// Create a callback function which will be invoked when addValue event is listened.
var add_value_callback = function (valueNumber) {
    // Only print the number value in console log.

// Register add_value_callback function as the addValue event listener.
counter.addListener('addValue', add_value_callback);

// Call counter's addValue method twice, you can see the console log output.

// Remove the callback function for addValue event.
counter.removeListener('addValue', add_value_callback);

// Call addValue method again, you can not see number output in console log because the event listener has been removed.

Below is the example output in log console.


Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.