๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Frontend/JavaScript

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] DOM ์†์„ฑ์— ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ ์—ฐ๊ฒฐํ•˜๊ธฐ

by YWTechIT 2022. 3. 21.
728x90

๐Ÿ“ DOM ์†์„ฑ์— ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ ์—ฐ๊ฒฐํ•˜๊ธฐ

์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ๋ฅผ DOM์š”์†Œ์— ์—ฐ๊ฒฐํ•  ๋•Œ ๋ณดํ†ต 2๊ฐ€์ง€ ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•˜๋Š”๋ฐ, ์ฒซ ๋ฒˆ์งธ๋กœ on์†์„ฑ๊ณผ, ๋‘๋ฒˆ์งธ๋Š” addEventListener์ด๋‹ค. ์ „์ž์˜ ๊ฒฝ์šฐ ๋น ๋ฅด์ง€๋งŒ ์ง€์ €๋ถ„ํ•œ ๋ฐฉ๋ฒ•์ด๋ผ๊ณ  ๋งํ•œ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด ondblclick, onmouseover, onblur, onfocus ์†์„ฑ์ด ์žˆ๋‹ค.

const button = document.querySelector("button");
button.onclick = () => {
    console.log("Click managed using onclick property");
}

 

์ด๋Ÿฐ ํ•ด๊ฒฐ์ฑ…์€ ์ž˜ ๋™์ž‘ํ•˜๋”๋ผ๋„ ์ผ๋ฐ˜์ ์œผ๋กœ ๋‚˜์œ ๊ด€ํ–‰์œผ๋กœ ๊ด€์ฃผ ๋˜๋Š”๋ฐ, ๊ทธ ์ด์œ ๋Š” ์†์„ฑ์„ ์‚ฌ์šฉํ•˜๋ฉด ํ•œ๋ฒˆ์— ํ•˜๋‚˜์˜ ํ•ธ๋“ค๋Ÿฌ๋งŒ ์—ฐ๊ฒฐํ•  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ๋”ฐ๋ผ์„œ ์ฝ”๋“œ๊ฐ€ onclick ํ•ธ๋“ค๋Ÿฌ๋ฅผ ๋ฎ์–ด์“ฐ๋ฉด ์›๋ž˜ ํ•ธ๋“ค๋Ÿฌ๋Š” ์˜์›ํžˆ ์†์‹ค๋œ๋‹ค.

728x90

๊ทธ๋ž˜์„œ ๋” ๋‚˜์€ ์ ‘๊ทผ ๋ฐฉ์‹์ธ addEventListener ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค. addEventListener์˜ ์ฒซ ๋ฒˆ์งธ ๋งค๊ฐœ๋ณ€์ˆ˜๋Š” ์ด๋ฒคํŠธ ํƒ€์ž…์ด๊ณ , ๋‘ ๋ฒˆ์งธ ๋งค๊ฐœ๋ณ€์ˆ˜๋Š” ์ฝœ๋ฐฑ์ด๋ฉฐ ์ด๋ฒคํŠธ๊ฐ€ ํŠธ๋ฆฌ๊ฑฐ ๋  ๋•Œ ํ˜ธ์ถœ๋œ๋‹ค. ๋‹ค์Œ ์ฝ”๋“œ์ฒ˜๋Ÿผ ๋ชจ๋“  ํ•ธ๋“ค๋Ÿฌ๋ฅผ ์—ฐ๊ฒฐ ํ•  ์ˆ˜ ์žˆ๋‹ค.

const button = document.querySelector("button")
const firstHandler = () => {
    console.log("First Handler");
}
const secondHandler = () => {
    console.log("Second Handler");
}

button.addEventListener("click", firstHandler)
button.addEventListener("click", secondHandler)

 

๋‚˜์•„๊ฐ€ DOM์— ์š”์†Œ๊ฐ€ ๋” ์ด์ƒ ์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฉด ๋ฉ”๋ชจ๋ฆฌ ๋ˆ„์ˆ˜๋ฅผ ๋ฐฉ์ง€ํ•˜๊ณ ์ž ์ด๋ฒคํŠธ ๋ฆฌ์Šค๋„ˆ๋ฅผ ์‚ญ์ œํ•ด์•ผ ํ•˜๋Š”๋ฐ, ์ด๋•Œ removeEventListener ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค. ๋‹ค์Œ ์ฝ”๋“œ์—์„œ ๊ฐ€์žฅ ์ค‘์š”ํ•œ ์ ์€ ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ๋ฅผ ์ œ๊ฑฐํ•˜๋ ค๋ฉด removeEventListener๋ฉ”์„œ๋“œ์— ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ „๋‹ฌํ•  ์ˆ˜ ์žˆ๋„๋ก ์ด์— ๋Œ€ํ•œ ์ฐธ์กฐ๋ฅผ ์œ ์ง€ํ•ด์•ผ ํ•œ๋‹ค๋Š” ๊ฒƒ์ด๋‹ค.

const button = document.querySelector("button")
const firstHandler = () => {
    console.log("First Handler");
}
const secondHandler = () => {
    console.log("Second Handler");
}

button.addEventListener("click", firstHandler)
button.addEventListener("click", secondHandler)

window.setTimeout(() => {
    button.removeEventListener('click', firstHandler)
    button.removeEventListener('click', secondHandler)
    console.log("Removed Event Handlers");
 }, 1000)

 

Reference

  1. ํ”„๋ ˆ์ž„์›Œํฌ ์—†๋Š” ํ”„๋ก ํŠธ์—”๋“œ ๊ฐœ๋ฐœ - ํ”„๋ž€์„ธ์Šค์ฝ” ์ŠคํŠธ๋ผ์ธจ๋กœ
  2. https://developer.mozilla.org/ko/docs/Web/API/EventTarget/removeEventListener
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€