Search code examples
javascriptnode.jsclasseventsecmascript-6

What's the most compact way to add "events" to a JavaScript class in a Node.js module? (in ES6 and above env.)


Have been looking for the universal way to handle events in a class. To be exact, I'm making a node.js module and I want to be able to add multiple callbacks to certain events. Say, my source looks something like this:

class Example {
    constructor(...args) {
        // ...
    }
    doSomething(earg) {
        setTimeout(() => {
            // I want an event call here.
            // this.callEvent(eargs) or something like that, to pass 
            // down arguments to callbacks.
        }, 3000);
    }
    on(event, callback, watch) {
        // ...
    }

    once(event, callback, watch) {
        // ...
    }
}

const example = new Example();
example.on('doSomethingEnd', (earg) => console.log(':P', earg));

What's the most compact and modern way of achieving .ons and .onces in an ES6 and above environment and how to do "code editor autofill" for such? (For editors like Atom or VSCode, or any other that have syntax hinting).


Solution

  • Solved it, Node has a built in class for that (props to @Bergi):

    const { EventEmitter } = require('events');
    
    class Example extends EventEmitter {
        constructor(...args) {
            // ...
        }
        doSomething(earg) {
            setTimeout(() => {
                this.emit('<example>', 'arg0')
            }, 3000);
        }
    }
    
    const example = new Example();
    example.on('<example>', (earg) => { /* ... */ });