Home > Net >  Is there a way to make my own onevent handler for a class in javascript
Is there a way to make my own onevent handler for a class in javascript

Time:10-15

for example, I am trying to make something like this:

connection = new WorkshopConnect(thisWorkshopID);

    connection.onopen = function (evt) {
        log(`connection.onopen:`, evt);
    };

Where I can call a class and then call an event handler with the class property, and then when a certain event happens within the class. It will fire the onopen property, which will then call the function it is attached to.

I hope I explained it in a way you can understand.

CodePudding user response:

Absolutely! There are many ways of acomplishing this. The easiest way (in my opinion) is to create a class such as this:

class EventEmitter {
    emit(event, ...args) {
        const handler = this['on'   event];
        if (typeof handler == 'function') {
            handler(...args);
        }
    }
}

Then extend the class and call the event when necessary:

class Class extends EventEmitter {
    constructor() {
        super();
        setTimeout(this.emit.bind(this), 1e3, 'ready');
    }
}

And finally, listen for the event.

const instance = new Class();
instance.onready = function() {
    console.log('Ready!');
}

If you want a proper EventEmitter with this included, it wouldn't be too hard to implement into the EventEmitter class. Hope it helps!

  • Related