Skip to content

Instantly share code, notes, and snippets.

@deepakkoirala
Forked from umidjons/extend-eventemitter.md
Created September 11, 2019 21:29
Show Gist options
  • Save deepakkoirala/9b7d4d86ef31469e0bf7bccb3ebe1b81 to your computer and use it in GitHub Desktop.
Save deepakkoirala/9b7d4d86ef31469e0bf7bccb3ebe1b81 to your computer and use it in GitHub Desktop.
Extending EventEmitter example

Extending EventEmitter example

"use strict";

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

class MyClass extends EventEmitter {
    /**
     * Create MyClass instance
     * @param {int} start counter's start value
     * @param {int} interval interval in milliseconds
     */
    constructor(start, interval = 3000) {
        super();
        this.counter = start;
        this.interval = interval;
    }

    /**
     * Some worker method, that emits myEvent event with counter's value
     */
    startWork() {
        setInterval(()=> {
            this.emit('myEvent', this.counter++);
        }, this.interval);
    }
}

var myObj = new MyClass(10, 1000);

// subscribe to the event
myObj.on('myEvent', (data)=> {
    console.log('Event fired:', data);
});

// start very important work
myObj.startWork();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment