侦听 JavaScript 中的所有事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27321672/
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-23 00:00:58  来源:igfitidea点击:

Listen for all events in JavaScript

javascript

提问by user3780616

I'm trying to figure out how to listen for all events on a JavaScript object.

我试图弄清楚如何侦听 JavaScript 对象上的所有事件。

I know that I can add individual events with something like this

我知道我可以添加这样的单个事件

element.addEventListener("click", myFunction);
element.addEventListener("mouseover", myFunction);
...

I'm trying to figure out if there is a catch-all, I'd like to do something like this:

我想弄清楚是否有一个包罗万象的东西,我想做这样的事情:

// Begin pseudocode
var myObj = document.getElementById('someID');

myObj.addEventListener(/*catch all*/, myFunction);

function myFunction() {
  alert(/*event name*/);
}
// End pseudocode

回答by ryanpcmcquen

A more modern rewrite of @roman-bekkiev's answer:

对@roman-bekkiev 的回答进行更现代的重写:

Object.keys(window).forEach(key => {
    if (/^on/.test(key)) {
        window.addEventListener(key.slice(2), event => {
            console.log(event);
        });
    }
});

Note that you can further customize what you want to catch, for example:

请注意,您可以进一步自定义要捕获的内容,例如:

/^on(key|mouse)/.test(key)

/^on(key|mouse)/.test(key)

回答by Roman Bekkiev

To pick up standard element's events.

获取标准元素的事件。

var myObj = document.getElementById('someID');
for(var key in myObj){
    if(key.search('on') === 0) {
       myObj.addEventListener(key.slice(2), myFunction)
    }
}

But as @jeremywoertink mentioned any other events are also possible.

但正如@jeremywoertink 提到的,任何其他事件也是可能的。

回答by Mosho

You should probably pick the events you want to listen to, put them into an array and iterate over each:

您可能应该选择要收听的事件,将它们放入一个数组中并遍历每个:

['click','mouseover'].forEach(function(ev) {
    el.addEventListener(ev, function() {
        console.log('event:', ev)
    })
})

回答by jeremywoertink

You could use EventEmitter2which does wildcards. The problem with doing a catchall like you're talking about is that there are so many events, and you can create your own. You'd have to make an array of specifically which events you're talking about, iterate over that, and bind each one individually.

您可以使用执行通配符的EventEmitter2。像你所说的那样做一个包罗万象的问题是有很多事件,你可以创建自己的。您必须制作一组您正在谈论的具体事件,对其进行迭代,然后单独绑定每个事件。

回答by Cody

I hate that this problem persists without a native or elegant solution.

我讨厌这个问题在没有原生或优雅的解决方案的情况下仍然存在。

A Better Solution?

更好的解决方案?

This allows you to subscribe to a single CustomEventfor any EventTargetusing target.addEventListener('*', ...).

这允许您CustomEvent为任何EventTarget使用订阅单个target.addEventListener('*', ...)

    clear();

    /**
     * @param : source := EventTarget
     *  *   EventTarget.prototype
     *  *   Node (Element, Attr, etc)
     * @usage : [Node].addEventListener('*', ({ detail: e }) => {...}, false);
     */
    function proxyEventTargetSource(source) {
        var emit = source.dispatchEvent;  // obtain reference

        function proxy(event) {
            var { type } = event, any = new CustomEvent('*', { detail: event });  // use original event as detail
            if (!{ '*': true }[ type ]) emit.call(this, any);  // only emit "any" if type is not any.type ('*')
            return emit.call(this, event);
        }

        if ({ 'dispatchEvent': true }[ emit.name ]) source.dispatchEvent = proxy;  // attempt overwrite only if not already set (avoid rewrapping)
        return (source.dispatchEvent === proxy);  // indicate if its set after we try to
    }

    // proxyEventTargetSource(EventTarget.prototype);  // all targets
    proxyEventTargetSource(document);  // single target
    var e = new CustomEvent('any!', { detail: true });
    document.addEventListener('*', (e) => console.log('type: %s, original: %s, e: %O', e.type, e.detail.type, e), false);
    document.dispatchEvent(e);

Granted, a more native or [perhaps] more elegant way would be to use a native Proxyon applyfor the target's dispatchEventmethod, but that would maybe convey less for the sake of this post.

当然,更原生或更优雅的方式是使用原生Proxyonapply作为目标的dispatchEvent方法,但为了这篇文章,这可能传达的更少。

Gist: https://gist.github.com/cScarlson/875a9fca7ab7084bb608fb66adff0463

要点:https: //gist.github.com/cScarlson/875a9fca7ab7084bb608fb66adff0463

Known Issues

已知的问题

Apparently, this only works while driving event-dispatching through EventTargets's dispatchEventmethod. That is, naturally triggering events through mouse events (for instance) does not work. There would need to be a way to wrap the internal method being called by natural event-triggers.

显然,这仅在通过EventTargetsdispatchEvent方法驱动事件分派时有效。也就是说,通过鼠标事件(例如)自然触发事件是行不通的。需要有一种方法来包装由自然事件触发器调用的内部方法。

That being said, if you have a way around this, please show what you have in another answer.

话虽如此,如果您有办法解决这个问题,请在另一个答案中展示您的想法。

回答by Mario Gomez

//listening for all click events on the document
   document.addEventListener('click', function (event) {

    //filtering for only events that happen on elements that contain the class
    //view_btn.          
  if (event.target.classList.contains( 'view_btn' )){
//logging out the id of the element        
          var id_of_clicked_element = event.target.getAttribute("id"); //
          console.log("button clicked has is of " + id_of_clicked_element)

        }
    });