我正在努力争取事件。我希望A类解雇活动,B类应捕获该事件,并将事件数据传递给其自己的方法:
class ClassA {
constructor() {
window.addEventListener("fire", function (e) { this.fired(e.detail); }); //<--- not working
}
fired(data) {
console.log("fired by: "+data);
}
}
class ClassB {
constructor() {
var event = new CustomEvent("fire", { detail: { data: "John Doe" } } );
window.dispatchEvent(event);
console.log("fired");
}
}
new ClassA(); //adds event listener
new ClassB(); //event dispatch
它看起来范围并不指类。您可以在班级中使用箭头功能:
window.addEventListener("fire", (e) => { this.fired(e.detail); })