Home > front end >  Custom Event on JavaScript Class
Custom Event on JavaScript Class

Time:05-23

How can I create an event that is attached to a class object?

I have to create a class that has an event that should be called at a certain time. The class looks like this and should call the event newMember when a new one is added. What works is that I attach a custom event to the window and call it which is not my goal.

Not NodeJS.

class Room {
    constructor() {
        this.members = {}
    }
    addMember(data) {
        if (!this.members[data.remotesid]) {
            this.members[data.socket] = data.identity
            //this.dispatchEvent();
        } else {
            console.log('Member already in room')
        }
    }
}

CodePudding user response:

After being advised that I need to extend my class with EventTarget. I have now worked out this working solution.

class Room extends EventTarget {
    #event;
    constructor() {
        super();
        this.members = {}
    }
    addMember(data) {
        if (!this.members[data.remotesid]) {
            this.members[data.socket] = data
            this.#event = new CustomEvent("newMember", { detail: data });
            this.dispatchEvent(this.#event);
        } else {
            console.log('Member already in room')
        }
    }
}


var room = new Room();

room.addEventListener("newMember", function (e) {
    console.log("newMember event ", e);
});
  • Related