调度来自 JavaScript 中的自定义对象的事件



是否可以在对象中创建自定义事件?像这样的东西

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);
}

在 mai 中.js创建一个myCustomClass

myCustomClass = new myCustomClassr(param);
myCustomClass.addEventListener('started', function () {
console.log("started");
});
myCustomClass.start();

使用此代码,我收到一个错误,告诉我dispatchEvent不是函数

dispatchEvent 并非在所有 JavaScript 对象上都可用。这是非常可行的,但您需要从事件发射器继承,因此您的类具有事件功能。

JS中有无数的事件发射器,你也可以很容易地编写自己的东西。

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

最新更新