Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

68
Views
Custom Event on JavaScript Class

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')
        }
    }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!