How to use JavaScript EventTarget?

前端 未结 10 1814
一生所求
一生所求 2020-12-01 03:53

I would like to create a custom event emitter in my client-side programs. I am referencing this (sparse) documentation for EventTarget

My implementation atte

10条回答
  •  佛祖请我去吃肉
    2020-12-01 04:23

    EventType() constructor is now supported in most modern browsers.

    For the browsers which still do not support it, there is a polyfill available.

    This means that it's as simple as:

    var e = new EventTarget();
    
    e.addEventListener("hello", function() {
      console.log("hello there!");
    });
    
    e.dispatchEvent(new CustomEvent("hello"));
    // "hello there!"
    

    For Internet Explorer, which doesn't support CustomEvent being used this way, there is code for a polyfill listen on the MDN page or a package on GitHub and npm

    For the sake of completeness, in Node or an Electron app you would do

    var EventEmitter = require('events');
    
    var e = new EventEmitter();
    
    e.addListener("hello", function() {
      console.log("hello there!");
    });
    
    e.emit("hello")
    // "hello there!"
    
    

提交回复
热议问题