환상적으로 마법 같은 handleEvent 함수

3890 단어 javascriptwebdev
한 번 보자!



몇 년 전에 이 사실을 알았을 때 어떻게 반응했는지 기억합니다. 또한 저는 여전히 장엄한 콧수염을 가지고 있었습니다.



맞습니다. 작동합니다. 이상하지만 작동합니다.

객체를 핸들러로 addEventListener로 설정하고 해당 객체에 이름이 handleEvent인 속성이 있고 해당 속성이 function 유형인 경우 event가 자동으로 전송됩니다.

이것이 작동하는 이유(및 모든 브라우저에서 작동):

The need for compatibility with legacy content required EventListener to accept both a function and an object with a handleEvent() property function.



EventListener on MDN

이것에 대한 또 다른 좋은 점은 이것이 this가 계속 작동한다는 것입니다.



따라서 올바른 범위에 있는지 확인하기 위해 bind(this)가 필요하지 않습니다. 또한 이벤트는 removeEventListener('click', this)로 쉽게 제거됩니다.

이벤트를 처리하기 위해 다른 기능을 사용하는 대신 단일handleEvent 기능을 사용하여 모든 종류의 이벤트를 라우팅할 수 있습니다.

class MyClass {

  constructor() {

    // Get a reference to the button node
    const btn = document.querySelector('button');
    const input = document.querySelector('input');

    // Handle clicks by this
    btn.addEventListener('click', this);

    // Handle input by this
    input.addEventListener('input', this);

  }

  handleEvent(event) {
    if (event.type === 'click') {
      // handle button clicks 
    }
    else if (event.type === 'input') {
      // handle text input
    }
  }

}


이것이 당신이 작업할 수 있는 몇 가지 흥미로운 새로운 아이디어를 촉발시켰기를 바랍니다!

좋은 웹페이지 즐겨찾기