-2

If a custom event created via CustomEvent is dispatched, what is the method to cancel it in listeners to prevent event's main purpose?

E.g. An overlay is clicked by a user, then it emits an event, but it must be up to some code to decide if to hide the overlay or leave it untouched.

UPDATE It's a share-knowledge question, I know the answer but try to impart it to the others.

Dmitry Nevzorov
  • 595
  • 8
  • 16
  • Why did you ask a question while you already know the answer yourself? Also it's a duplicate – Sander Visser Dec 21 '18 at 18:00
  • 1
    @SanderVisser - That (the ask-and-answer part) is **perfectly fine** on SO, and [actively encouraged](https://stackoverflow.com/help/self-answer). The duplicate part is fine or not fine depending (for self-answer, usually not fine). (Duplicates can help direct people to the already-asked question and its answers.) Please identify the duplicate so people can vote appropriately. – T.J. Crowder Dec 21 '18 at 18:00
  • @T.J.Crowder ok ok, it's more that the question was asked and the answer 1 sec later. I know that you can answer you own question if you found the answer yourself. But this felt a bit strange. – Sander Visser Dec 21 '18 at 18:03
  • 1
    @SanderVisser - The system explicitly encourages answering the question **as** you ask it -- e.g., sharing knowledge you already have, but in Q&A form. When you're asking a question, it has a button to press if you want to provide the answer at the same time. Then it publishes both at once. – T.J. Crowder Dec 21 '18 at 18:08
  • 1
    @T.J.Crowder Didn't know thanks! – Sander Visser Dec 21 '18 at 18:09
  • 1
    @Sander Visser I was looking for a quick answer here but didn't found any about vanilla JS, then, after own search, decided that I'm not alone and shared the knowledge. Can you give a link with the duplicate? I would ask a moderator to mark my question as a duplicate – Dmitry Nevzorov Dec 24 '18 at 13:34
  • Possible duplicate of [How to fire custom cancelable event](https://stackoverflow.com/questions/42732247/how-to-fire-custom-cancelable-event) – Dmitry Nevzorov Dec 24 '18 at 13:47

1 Answers1

0

We need to configure the event as cancellable

// create an event
let awesomeEvent = new CustomEvent('some_awesome_event', {
    cancelable: true
})
// emit
let isAllowed = window.dispatchEvent(awesomeEvent)

Call preventDefault inside any event listener to cancel it.

window.addEventListener('some_awesome_event', event => {
    event.preventDefault()
})

Then it is possible to check whether the event was cancelled with the result returned from dispatchEvent

let isAllowed = window.dispatchEvent(awesomeEvent)
if(isAllowed){
    // do some default things
}
else {
    // just an example
    console.log('Oops! The event was cancelled, nothing to do...')
}

MDN guide for events creation and triggering

preventDefault documentation

cancellable interface docs

Dmitry Nevzorov
  • 595
  • 8
  • 16