简体   繁体   中英

Fire event inside handler

I'm trying to fire event inside event handler in this way (with no luck)...

<div id="test">
 <button onclick="this.dispatchEvent(new Event('btn-a'))">A</button>
 <button onclick="this.dispatchEvent(new Event('btn-b'))">B</button>
</div>
let test = document.getElementById("test")
test.addEventListener('btn-a', () => { console.log("A") })
test.addEventListener('btn-b', () => { console.log("B") })

Is it possible, and if it is, how to do it properly? Without jQuery please.

By default events created by Event don't bubble, due to that the event in your code will only fire one the button .

But you attache the listener to the parent of the button , so the event callback won't be called in this case.

You could set bubbles to true and it should work:

new Event('btn-b', {bubbles:true})

The event listener is attached to the parent rather than the button. You should be dispatching the event on the parentElement :

 let test = document.getElementById("test") test.addEventListener('btn-a', () => { console.log("A") }) test.addEventListener('btn-b', () => { console.log("B") })
 <div id="test"> <button onclick="this.parentElement.dispatchEvent(new Event('btn-a'))">A</button> <button onclick="this.parentElement.dispatchEvent(new Event('btn-b'))">B</button> </div>

Alternatively you can set the third parameter in addEventListener to true :

 let test = document.getElementById("test") test.addEventListener('btn-a', () => { console.log("A") }, true) test.addEventListener('btn-b', () => { console.log("B") }, true)
 <div id="test"> <button onclick="this.dispatchEvent(new Event('btn-a'))">A</button> <button onclick="this.dispatchEvent(new Event('btn-b'))">B</button> </div>

Why dont initial the onclick with javascript too?

Then you see what is your problem:) this will refere to the button, but you are listening on the wrapper div.

Try this one:

<div id="test">
 <button data-event="btn-a">A</button>
 <button data-event="btn-b">B</button>
</div>

JS:

let test = document.getElementById("test")
test.addEventListener('btn-a', () => { console.log("A") })
test.addEventListener('btn-b', () => { console.log("B") })

let buttons = test.querySelectorAll('button');

buttons.forEach(button => 
    button.addEventListener('click', e => {
       test.dispatchEvent(new CustomEvent(e.target.dataset.event));
    });
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM