9

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);
});
gyre
  • 16,369
  • 3
  • 37
  • 47
behzad besharati
  • 5,873
  • 3
  • 18
  • 22
  • Please create a [mcve] instead of posting incomplete code - Here is a jQuery way: http://stackoverflow.com/questions/2229647/jquery-how-do-i-use-event-preventdefault-with-custom-events – mplungjan Mar 11 '17 at 06:48

2 Answers2

13

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'
)
gyre
  • 16,369
  • 3
  • 37
  • 47
7

CustomEvent constructor accepts CustomEventInit as second argument. CustomEventInit is an extension of EventInit described here https://developer.mozilla.org/en-US/docs/Web/API/Event/Event

In the end.

document.dispatchEvent(new CustomEvent('my-event', {cancelable: true}));
wookieb
  • 4,099
  • 1
  • 14
  • 17