Question 61
Question
Answer
// Create a custom Event class
class UserLoggedInEvent extends Event {
constructor(detail) {
super('userLoggedIn', { bubbles: true, composed: true }); // 'bubbles' = allows propagation to parent elements
this.detail = detail; // Store additional data about the event
}
}
// Element representing a login button (or any suitable target)
const loginButton = document.getElementById('loginButton');
loginButton.addEventListener('click', () => {
const userEmail = 'alice@example.com'; // Example logged-in user email
const loggedInEvent = new UserLoggedInEvent({ userEmail });
loginButton.dispatchEvent(loggedInEvent);
});
// Somewhere else in your code:
document.addEventListener('userLoggedIn', (event) => {
console.log(`User ${event.detail.userEmail} has logged in!`); // Access event data
// Perform other actions based on the login event
});Last updated