javascripteventsecmascript-6

How do you do custom events on a JavaScript (ES6) class?


When I search for custom events on JavaScript classes, I get a lot of old or incomplete results. MDN shows a custom event off of a dom element. Stackoverflow's top result is almost ten years old and it uses the pre-ES6 syntax.

Is there a way of doing something like:

class Dog
{
  constructor(name)
  {
    this.name = name;
  }
  
  //something to expose bark event
  
}

const buddy = new Dog('buddy');
buddy.addEventListener("bark", function(e) {
  console.log(`${this.name} barked!`);
});


Solution

  • There are no events with a class. You can implement something that registers functions and you can call them when the method is triggered. Basic idea:

    class Animal {
      #registered = {};
      
      constructor(name)
      {
        this.name = name;
      }  
      
      addEventListener(name, callback) {
        if (!this.#registered[name]) this.#registered[name] = [];
        this.#registered[name].push(callback);
      }
      triggerEvent(name, args) {
         this.#registered[name]?.forEach(fnc => fnc.apply(this, args));
      }
    }
    
    
    class Dog extends Animal
    {
      constructor(name)
      {
        super(name);
      }
      
      bark(){
        console.log('bark was called');
        this.triggerEvent('bark');
      }
    
      eat(what){
        console.log('eat was called', what);
        this.triggerEvent('eat', [what]);
      }
    
    }
    
    const buddy = new Dog('buddy');
    buddy.addEventListener("bark", function() {
      console.log(`${this.name} barked!`);
    });
    buddy.addEventListener("eat", function(item) {
      console.log(`${this.name} ate a ${item}!`);
    });
    buddy.bark();
    buddy.eat('bone');