【问题标题】:Dispatch event from custom objects in JavaScript从 JavaScript 中的自定义对象调度事件
【发布时间】:2020-02-04 15:31:01
【问题描述】:

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

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 不是函数

【问题讨论】:

标签: javascript dom-events event-dispatching


【解决方案1】:

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

在 JS 中有无数的 Event Emitter 东西,你也可以很容易地编写自己的。

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

【讨论】:

    猜你喜欢
    • 2011-11-12
    • 2022-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多