환상적으로 마법 같은 handleEvent 함수
3890 단어 javascriptwebdev
몇 년 전에 이 사실을 알았을 때 어떻게 반응했는지 기억합니다. 또한 저는 여전히 장엄한 콧수염을 가지고 있었습니다.
맞습니다. 작동합니다. 이상하지만 작동합니다.
객체를 핸들러로
addEventListener
로 설정하고 해당 객체에 이름이 handleEvent
인 속성이 있고 해당 속성이 function
유형인 경우 event
가 자동으로 전송됩니다.이것이 작동하는 이유(및 모든 브라우저에서 작동):
The need for compatibility with legacy content required
EventListener
to accept both afunction
and anobject
with ahandleEvent()
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
}
}
}
이것이 당신이 작업할 수 있는 몇 가지 흥미로운 새로운 아이디어를 촉발시켰기를 바랍니다!
Reference
이 문제에 관하여(환상적으로 마법 같은 handleEvent 함수), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/rikschennink/the-fantastically-magical-handleevent-function-1bp4텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)