Skip to content

Instantly share code, notes, and snippets.

@YankeeTube
Created July 23, 2022 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YankeeTube/072039d3158c79e4f9d29509affa49fe to your computer and use it in GitHub Desktop.
Save YankeeTube/072039d3158c79e4f9d29509affa49fe to your computer and use it in GitHub Desktop.
click outside vanilla ts
function clickOutSideHandler(elem: HTMLElement, e: Event) {
const isInside = elem?.contains(e.target as HTMLElement)
const handler = clickOutSideHandler.bind(null, elem);
if (!isInside) {
const closeEvent = new CustomEvent('CLOSE', {detail: e})
elem.dispatchEvent(closeEvent)
} else {
document.addEventListener('click', handler, {once: true})
}
}
function clickOutside(elem: HTMLElement) {
const handler = clickOutSideHandler.bind(null, elem)
document.addEventListener('click', handler, {once: true})
}
export default clickOutside
@YankeeTube
Copy link
Author

Korean

bind가 포함된 handler는 더 이상 같은 context를 바라보지 않습니다.
그래서 addEventlistener와 removeEventlistener는 다른 함수를 호출하게 되기 때문에 이를 해결하는 가장 짧은 코드입니다.

once를 이용해서 한번만 호출하고 inside에 잡힌 경우 다시 이벤트를 재 등록합니다.
이 과정으로 인해 이벤트가 누적되어 동일 함수가 여러 번 반복되는 일은 없을거에요! :D

Eng

Handlers with bind no longer look at the same context.
So addeventlistener and removeeventlistener are the shortest code to solve this because they call different functions.

Use once to call once and re-register the event again if caught inside.
This process will accumulate events and will not cause the same function to repeat many times! :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment