Search code examples
javascripteventscustom-events

Custom Object events


I'm trying to emit custom events from my custom object like so:

var CustomObject = function () {
    this.customEvent = new Event('afterInit')
    /* init code goes here*/
    this.dispatchEvent(this.customEvent)
}

But my object cannot dispatch (i.e. dispatchEvent is not a property of my object) and I cannot bind to it. What is the correct syntax for firing custom events from custom objects?


Solution

  • Recently, EventTarget got a constructor, so you can actually use it for your JS object – before it was just an interface used only by DOM elements:

    class CustomObject extends EventTarget {
      constructor() {
        super();
        this.customEvent = new CustomEvent("afterinit");
      }
    
      init() {
        this.dispatchEvent(this.customEvent)
      }
    };
    
    let myObject = new CustomObject();
    myObject.addEventListener("afterinit", console.log);
    myObject.init();
    

    Unfortunately, the support of EventTarget's constructor is not good enough – see the link above –, and it's a Web API, means supported only in a browser's environment.