Skip to content

Instantly share code, notes, and snippets.

@umidjons
Created August 13, 2016 12:54
Show Gist options
  • Save umidjons/9ce1e39a88438cebf41479c9a43d8ba2 to your computer and use it in GitHub Desktop.
Save umidjons/9ce1e39a88438cebf41479c9a43d8ba2 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