How to use JavaScript EventTarget?

前端 未结 10 1795
一生所求
一生所求 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条回答
  •  -上瘾入骨i
    2020-12-01 04:25

    Here is how to do it using CustomEvent, cross-browser (fiddle):

    // listen to event
    window.addEventListener("say", function(e) { alert(e.detail.word); });
    
    // create and dispatch the event
    var event = document.createEvent("CustomEvent");
    event.initCustomEvent('say', true, true, 
        { "word": "Hello!" });
    
    window.dispatchEvent(event);
    

    You'd need to use window or document or any other existing DOM element to register listeneres and dispatch the event. EventTarget is not a object, it's an interface. Try accessing EventTarget in JavaScript console and you'll see that.

提交回复
热议问题