ReasonJun

javascript : event ( add, remove, dispatch, custom event) 본문

Frontend/Javasciprt

javascript : event ( add, remove, dispatch, custom event)

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

add / remove

//? .addEventListener()
// Registers to listen for events on the target.
// When an event specified in the target occurs, the specified function is called.

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

parentEl.addEventListener('cilck', () => {
  console.log('Parent');
});

childEl.addEventListener('cilck', () => {
  console.log('Child');
});

//? .removeEventListener()
// Removes the event listener registered on the target.
// It may be necessary to remove events registered for memory management.

// If you're going to remove it, it's a good idea to make it a function name that you can refer to.
const handler = () => {
  console.log('Parent!');
};

parentEl.addEventListener('click', handler);
childEl.addEventListener('click', () => {
  parentEl.removeEventListener('click', handler);
});

custom event / dispatch

//? dispatch

const child1 = document.querySelector('.child:nth-child(1)');
const child2 = document.querySelector('.child:nth-child(2)');

child1.addEventListener('click', (event) => {
  // force an event
  child2.dispatchEvent(new Event('click'));
  child2.dispatchEvent(new Event('wheele'));
  child2.dispatchEvent(new Event('keydown'));
});

child2.addEventListener('click', (event) => {
  console.log('Child2 Click');
});

child2.addEventListener('wheel', (event) => {
  console.log('Child2 wheel');
});

child2.addEventListener('keydown', (event) => {
  console.log('Child2 keydown');
});

//? custom event
child1.addEventListener('hello-world', (event) => {
  console.log('fire custom event');
  console.log(event.detail); // 123
});

child2.addEventListener('click', () => {
  child1.addEventListener(
    new CustomEvent('hello-world', {
      detail: 123, // Data can be passed only through the 'detail' attribute.
    })
  );
});
728x90
Comments