Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fire custom cancelable event

I know how to fire an event in JavaScript, but I don't know how to make it cancelable. via event.preventDefault() in event handler.

document.dispatchEvent(new CustomEvent("name-of-event", {}));

I have written the following code, but how is it possible in a native way, via event.preventDefault()?

document.dispatchEvent(new CustomEvent("my-event",function keepGoing(result){
  if(result){
      // continue ...
  }
}));

// And then in event listener:
document.addEventListener('my-event',function(event,keepGoing){
keepGoing(true);
// Or keepGoing(false);
});
like image 659
behzad besharati Avatar asked Mar 11 '17 06:03

behzad besharati


People also ask

How do I cancel a custom event?

If your custom event has the cancelable option set to true , you can use the Event. preventDefault() method to cancel it. document. addEventListener('my-custom-event', function (event) { // Cancel the event event.

How do I use dispatch event?

Calling dispatchEvent() is the last step to firing an event. The event should have already been created and initialized using an Event() constructor. Note: When calling this method, the Event. target property is initialized to the current EventTarget .

How do you define a custom event?

Custom event definitions are event definitions that have been created from scratch in the event definition editor rather than having been generated from existing events by the event definition generator.


1 Answers

The CustomEvent constructor takes a second options parameter, which you can use to make the event cancelable. See the article Creating and triggering events on MDN.

var event = new CustomEvent("my-event", {
  cancelable: true
})

document.addEventListener('my-event', function (event) {
   event.preventDefault()
})

console.log(
  document.dispatchEvent(event) ? 'Event was not cancelled' : 'Event was cancelled'
)
like image 128
gyre Avatar answered Sep 20 '22 18:09

gyre