0

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
yalpsideman
  • 23
  • 2
  • 6
  • Mr.doob has a [repository for this](https://github.com/mrdoob/eventdispatcher.js) – 2pha Feb 09 '20 at 23:38
  • possible approaches/solutions are provided by e.g. ... [_"How to make a Javascript class or object an event dispatcher?"_](https://stackoverflow.com/questions/73587926/how-to-make-a-javascript-class-or-object-an-event-dispatcher) ... or ... [_"Custom Object events"_](https://stackoverflow.com/a/51386367/2627243) ... or ... [_"How to implement an event dispatching system for ES/JS object types?"_](https://stackoverflow.com/questions/73894457/how-to-implement-an-event-dispatching-system-for-es-js-object-types/74140087#74140087) – Peter Seliger Oct 22 '22 at 13:51

1 Answers1

0

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

Fresheyeball
  • 29,567
  • 20
  • 102
  • 164