如何在 Javascript 中创建自定义事件类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2059456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:36:57  来源:igfitidea点击:

How do I create a custom event class in Javascript?

javascriptactionscript-3eventsjavascript-eventsevent-handling

提问by Josua Pedersen

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.

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

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.

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

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

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

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

Please no third-party library solutions.

请不要使用第三方库解决方案。

采纳答案by pfleidi

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

对我有用的方法是调用 document.createEvent(),初始化它并使用 window.dispatchEvent() 调度它。

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

回答by Rich Hauck

I'm a little late to the party here, but was searching for the same thing. I'm not keen on the first answer (above) because it relies upon the document to manage the custom event. This is dangerous because it's global and could potentially conflict with another script should that script coincidentally rely on the same custom event.

我参加聚会有点晚了,但正在寻找同样的东西。我不喜欢第一个答案(上面),因为它依赖于文档来管理自定义事件。这是危险的,因为它是全局的,并且如果该脚本巧合地依赖于相同的自定义事件,则可能与另一个脚本发生冲突。

The best solution I've found is here: Nicholas C. Zakas - Custom Events in Javascript

我找到的最佳解决方案在这里: Nicholas C. Zakas - Custom Events in Javascript

Unfortunately, since javascript doesn't support inheritance keywords, it's a bit messy with prototyping, but it definitely keeps things tidy.

不幸的是,由于 javascript 不支持继承关键字,因此原型设计有点混乱,但它绝对可以保持整洁。

回答by Drew Noakes

This is straightforward when using DOM elements to broker the events.

这在使用 DOM 元素来代理事件时很简单。

Given an element:

给定一个元素:

var element = document.querySelector('div#rocket');

For a client to subscribe:

对于要订阅的客户:

element.addEventListener('liftoff', function(e)
{
    console.log('We have liftoff!');
});

Then to dispatch/raise/fire the event, use this code:

然后要调度/引发/触发事件,请使用以下代码:

element.dispatch(new Event('liftoff'));

回答by WHill

I was just thinking of assigning a supported handler to a new namespace i.e. a reference to a supported event. The code below works (paste it in console of Chrome) but you can write it in a better format, and you should have additional helper methods (that can redefine themselves as well), for xBrowser support, and for sniffing support types (which after you've detected which path to use, you'll have the function redefine itself. I hope what I have below helps.

我只是想将受支持的处理程序分配给新的命名空间,即对受支持事件的引用。下面的代码有效(将其粘贴到 Chrome 的控制台中),但您可以以更好的格式编写它,并且您应该有额外的辅助方法(也可以重新定义自己),用于 xBrowser 支持和嗅探支持类型(之后您已经检测到要使用的路径,您将重新定义函数本身。我希望我下面的内容有所帮助。

var de = document.documentElement || document.getElementsByTagName[0];

function all(){ console.log('all') };

var customEventForSomeSpecificElement = function customEventForSomeSpecificElement() {
    return ({
            customEvent: function() {
                if ('onclick' in de ) {
                    return 'click';
                }
            },
            init: function(){ return this.customEvent(); }
        }).init();
}();

de.addEventListener(customEventForSomeSpecificElement, all, false);

回答by nicholas

This by John Resig:

约翰·雷西格 (John Resig) 的这篇文章:

function addEvent( obj, type, fn ) {
  if ( obj.attachEvent ) {
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
    obj.attachEvent( 'on'+type, obj[type+fn] );
  } else
    obj.addEventListener( type, fn, false );
}
function removeEvent( obj, type, fn ) {
  if ( obj.detachEvent ) {
    obj.detachEvent( 'on'+type, obj[type+fn] );
    obj[type+fn] = null;
  } else
    obj.removeEventListener( type, fn, false );
}

More at his blog post at http://ejohn.org/projects/flexible-javascript-events/.

更多信息参见他在http://ejohn.org/projects/flexible-javascript-events/ 的博客文章。

回答by Andris

It's not so hard actually - there isn't so many event definitions, only three versions. The first one is the corect one (addEventListener), then there's the IE way (attachEvent) and then there's the compatibility way for older browser (element.onevent = function)

实际上并没有那么难——没有那么多事件定义,只有三个版本。第一个是正确的(addEventListener),然后是 IE 方式(attachEvent),然后是旧浏览器的兼容方式(element.onevent = function

So a complete event handling solution would look something like this:

所以一个完整的事件处理解决方案看起来像这样:

setEvent = function(element, eventName, handler){
  if('addEventListener' in element){
    //W3
    element.addEventListener(eventName,handler,false);
  }else if('attachEvent' in elm){
    //IE
    elm.attachEvent('on'+eventName,handler)
  }else{
    // compatibility
    elm['on'+eventName] = handler;
  }
}

and to clear events:

并清除事件:

clearEvent = function(element, eventName, handler){
  if('removeEventListener' in element){
    //W3
    element.removeEventListener(eventName,handler,false);
  }else if('detachEvent' in elm){
    //IE
    elm.detachEvent('on'+eventName,handler)
  }else{
    // compatibility
    elm['on'+eventName] = null;
  }
}

and an example:

和一个例子:

setEvent(document, "click", function(){alert('hello world!');});
clearEvent(document, "click", function(){alert('hello world!');});

This is not really a complete example though since the compatibility handler always overwrites the previous events (it's not appending actions, it's overwriting) so you probably would like to check if a handler is already set and then save it into some temporary variable and fire it inside the event handler function.

这并不是一个完整的例子,因为兼容性处理程序总是覆盖以前的事件(它不是附加操作,它是覆盖)所以你可能想检查一个处理程序是否已经设置,然后将它保存到某个临时变量中并触发它在事件处理函数内部。