简体   繁体   中英

Dispatch event from custom objects in JavaScript

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM