2

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')
        }
    }
}
1
  • when a member is added to a Room. Like this var myRoom = new Room() myRoom.addeventlistener('newMember', (member) => { console.log(member); }) Commented May 21, 2022 at 9:18

1 Answer 1

4

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, had the same issue and wouldn't have figured it out without this!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.