Question 64
Question
How would you implement a custom event that bubbles up and can be canceled?
Answer
Custom events in JavaScript give you great flexibility. Here's how to implement one that bubbles up and can be canceled:
// Create the custom event class
class MyCustomEvent extends Event {
constructor(type, detail) {
super(type, { bubbles: true, cancelable: true }); // Set 'bubbles' for bubbling, 'cancelable' for cancellation
this.detail = detail;
}
}
// Example usage:
const parentElement = document.getElementById('myParent'); // Or any element you want
parentElement.addEventListener('myCustomEvent', (event) => {
console.log('Parent Element:', event.type, 'Detail:', event.detail);
if (event.cancelable && !someCondition()) {
// If cancellation is possible and the condition is not met, cancel the event:
event.preventDefault();
}
});
document.addEventListener('myCustomEvent', (event) => {
console.log('Document Element:', event.type, 'Detail:', event.detail);
});
// Trigger the custom event
const childElement = parentElement.querySelector('.child'); // Or any element that triggers it
childElement.addEventListener('click', () => {
const myEvent = new MyCustomEvent('myCustomEvent', { message: 'This is a custom event!' });
parentElement.dispatchEvent(myEvent);
});
Explanation:
bubbles: true
: This ensures the event propagates up the DOM tree from the triggering element to its parent, and so on.cancelable: true
: Allows the event to be canceled by callingevent.preventDefault()
. This is often used for situations where you want to stop a default behavior or prevent further event handling after a certain point.
Key Points:
Cancellation Logic (
if (event.cancelable && !someCondition())
): You can customize the cancellation logic based on your application's requirements. The example checkssomeCondition()
before callingevent.preventDefault()
. This condition could be anything that determines whether you want to cancel the event or not.
Last updated