如何在 Javascript 中创建自定义事件类? [英] How do I create a custom event class in Javascript?
本文介绍了如何在 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 want to 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屋!
查看全文