Sobes.tech
Junior

What is the event-driven model in the browser?

sobes.tech AI

Answer from AI

Method of handling user interactions (clicks, input, hover) and system events (page load, errors) in a web browser.

Main concepts:

  • Event: An action that occurred.
  • Event handler: A function that executes when the event occurs.
  • Event object: Passed to the handler and contains information about the event (type, element, coordinates, etc.).

Standard event flow:

  1. Capturing phase: The event descends from the topmost DOM element (Window, Document) to the target element. Handlers at this stage are triggered first.
  2. Target phase: The event reaches the target element - the element where it occurred.
  3. Bubbling phase: The event bubbles up from the target element back through the DOM tree to Window. Handlers at this stage are triggered after the capture and target phases.

Adding handlers:

  • HTML attributes (onclick, onload): Deprecated method, not recommended for complex applications.
  • DOM element properties (element.onclick): You can assign only one handler per event type for an element.
    // Example
    const button = document.querySelector('button');
    button.onclick = function() {
        alert('Button clicked!');
    };
    
  • addEventListener method: Preferred way. Allows adding multiple handlers for one event and controlling the phase of handling (capture or bubbling).
    // Example
    const button = document.querySelector('button');
    button.addEventListener('click', function(event) {
        console.log('Button clicked!', event);
    }, false); // false - bubbling, true - capturing
    

removeEventListener method is used to remove handlers.

Event delegation: Attaching a single handler to a parent element to handle events from child elements. Saves resources and simplifies work with dynamic content.

// Delegation example
const list = document.querySelector('ul');
list.addEventListener('click', function(event) {
    if (event.target.tagName === 'LI') {
        console.log('List item clicked:', event.target.textContent);
    }
});