[英]Dispatch event from custom objects in 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 对象都可用。 这是非常可行的,但是您需要从 Event Emitter 继承,因此您的类具有事件功能。
JS 中有无数的 Event Emitter 东西,你也可以很容易地编写自己的。
https://netbasal.com/javascript-the-magic-behind-event-emitter-cce3abcbcef9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.