Reputation: 6910
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);
});
Upvotes: 11
Views: 3711
Reputation: 16779
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'
)
Upvotes: 14
Reputation: 4489
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}));
Upvotes: 7