我如何在JavaScript中创建一个自定义事件类?自定义、创建一个、事件、如何在

2023-09-08 12:02:47 作者:风吹裤裆毛飞扬

如何创建类似于ActionScript中的自定义事件类?我的意思是,我可以用它来火了我自己的事件类,发送必要的数据。

How do I create a custom event class similar to ActionScript? What I mean by that is a class that I can use to fire off my own events, send the necessary data.

我不希望使用像YUI或jQuery的第三方库去做。我的目标是能够发送看起来像这样的事件。

I don't wanna use third-party libraries like YUI or jQuery to do it. My goal is to be able to send a event that looks like this.

document.addEventListener("customEvent", eventHandler, false);

function eventHandler(e){
    alert(e.para1);
}

document.dispatchEvent(new CustomEvent("customEvent", para1, para2));

请没有第三方库的解决方案。

Please no third-party library solutions.

推荐答案

这是为我工作的方法是调用document.createEvent(),初始化它,并派遣其与window.dispatchEvent()。

A method that worked for me was to call document.createEvent(), init it and dispatch it with window.dispatchEvent().

  var event = document.createEvent("Event");
  event.initEvent("customEvent", true, true);
  event.customData = getYourCustomData();
  window.dispatchEvent(event);