Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defaultPrevented check in custom event

When emitting a custom event with Javascript, the defaultPrevented property is always false. Here is a short example that shows this behaviour:

var event = new CustomEvent("my-event", {detail: "something"});

document.addEventListener("my-event", function(ev) {
    ev.preventDefault();
    console.log(ev.detail);
});

document.dispatchEvent(event); // => "something" from console.log above
console.log(event.defaultPrevented); // => false

There is a link in MDN for CustomEvent.initCustomEvent() that has an argument cancelable (which I'm guessing is the problem here), but the method is deprecated. How can I check if preventDefault was called in a custom event?

like image 509
user3696012 Avatar asked Oct 19 '25 13:10

user3696012


1 Answers

The second argument for the CustomEvent constructor accepts an object with the following properties:

  • bubbles - Boolean indicating if the event should buble

  • cancelable - Boolean indicating if the event is cancelable (here is the problem I had)

  • detail - Any custom data you want to pass along with the event.

In the example above, just add cancelable and it gives the correct output:

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

document.addEventListener("my-event", function(ev) {
    ev.preventDefault();
    console.log(ev.detail);
});

document.dispatchEvent(event); // => "something" from console.log above
console.log(event.defaultPrevented); // => true
like image 161
user3696012 Avatar answered Oct 21 '25 01:10

user3696012