我如何在JavaScript中创建一个自定义事件类? [英] How do I create a custom event class in Javascript?

查看:231
本文介绍了我如何在JavaScript中创建一个自定义事件类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建类似于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);

这篇关于我如何在JavaScript中创建一个自定义事件类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆