Dispatch event from custom objects in JavaScript

740 Views Asked by At

Is it possible to create custom events in objects? Something like this

var myCustomClass = function (param) {
  this.param = param;
};

myCustomClass.prototype.start = function(){
//Do staff
//fire event started
let event = new Event("started", {isStarted: true});
  this.dispatchEvent(event);
}

And in mai.js create an instance of myCustomClass

myCustomClass = new myCustomClassr(param);

myCustomClass.addEventListener('started', function () {
console.log("started");
});

myCustomClass.start();

With this code I am getting an error telling me that dispatchEvent is not a function

1

There are 1 best solutions below

0
Fresheyeball On

dispatchEvent is not available on all JavaScript objects. This is very doable, but you need to inherit from an Event Emitter, so your class has event functionality.

There are zillions of Event Emitter things in JS, and you can also write your own pretty easily.

https://netbasal.com/javascript-the-magic-behind-event-emitter-cce3abcbcef9