ReasonJun

javascript : event (delegation, event bubbling) 본문

Frontend/Javasciprt

javascript : event (delegation, event bubbling)

ReasonJun 2023. 6. 8. 18:37
728x90

delegation

// event delegation
// If you need to handle events on multiple elements in a similar pattern,
// You can use the event delegation pattern, controlled by a single ancestor element.

const parentEl = document.querySelector('.parent');
const childEls = document.querySelectorAll('.child');

// Event registration for all targets!
childEls.forEach((el) => {
  el.addEventListener('click', (event) => {
    console.log(event.target.textContent);
  });
});

// Delegating events to ancestor elements
// It can have the same effect as above.
parentEl.addEventListener('click', (event) => {
  const childEl = event.target.closest('.child');
  if (childEl) {
    console.log(childEl.textContent);
  }
});

event bubbling => capture / stopPropagation

// Prevent event propagation (bubbles)

parentEl.addEventListener('click', (event) => {
  event.stopPropagation();
});

// Fixed order of events (allows higher level events to fire first, starting with upper level options with 'capture' set)
document.window.addEventListener('click', (event) => {
  console.log('window');
});
document.body.addEventListener(
  'click',
  (event) => {
    console.log('body');
  },
  { capture: true }
); // body works first.

document.parentEl.addEventListener(
  'click',
  (event) => {
    console.log('parent');
  },
  { capture: true }
); // When the body is clicked, the parent is executed after the body, and the child window is executed.
document.childEl.addEventListener(
  'click',
  (event) => {
    console.log('child');
  },
  { capture: true }
);

// What happen in this code if i click child?

document.window.addEventListener(
  'click',
  (event) => {
    console.log('window');
  },
  { capture: true }
);
document.body.addEventListener(
  'click',
  (event) => {
    console.log('body');
    event.stopPropagation();
  },
  { capture: true }
); // window => body // end
document.parentEl.addEventListener(
  'click',
  (event) => {
    console.log('parent');
  },
  { capture: true }
);
document.childEl.addEventListener(
  'click',
  (event) => {
    console.log('child');
  },
  { capture: true }
);

// Other uses of capture
parentEl.addEventListener('click', handler, {
  capture: true,
});

parentEl.removeEventListener('click', handler); // Remove does not work due to the capture in the code above.
// to make it work
parentEl.removeEventListener('click', handler, {
  capture: true,
});
728x90
Comments