Question: 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?

Answer: 
Recently, [EventTarget](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/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.
Objects do not have events. You have to implement that functionality on your own, then you can create new objects that inherit that using the `class` syntax:

```
 const handlers = Symbol.for("handlers");

 class EventEmitter {
   constructor(...args) {
     super(...args);
     this[handlers] = new Map;
   }

   on(name, handler) {
     if(!this[handlers].has(name)) {
       this[handlers].set(name, [handler]);
     } else {
       this[handlers].get(name).push(handler);
     }
   }

   trigger(name, ...args) {
     for(const handler of this[handlers].get(name) || [])
        handler(...args);
   }
}

```

Which you can use as:

```
const obj = new EventEmitter();
obj.on("test", alert);
obj.trigger("test", "hello world!");

```

Or with inheritance:

```
class Custom extends EventEmitter { /*...*/ }

```