JavaScript Events

Event ์˜ ์ดํ•ด

Event model

: Event handler์™€ event API ์ •์˜

  • Web browser์™€ ์‹œ๊ธฐ๋ณ„๋กœ 3๊ฐ€์ง€์˜ ๋‹ค๋ฅธ event model ์กด์žฌ

    • why?

      • web browser์˜ ์ข…๋ฅ˜์— ๋”ฐ๋ผ ๋ณ€ํ™”๋˜๊ณ  ๊ฐœ์„ 

  • Event model์˜ ์ข…๋ฅ˜

    • ๊ธฐ๋ณธ ์ด๋ฒคํŠธ ๋ชจ๋ธ (Original event model)

      • ์˜ค๋ž˜๋œ ๋ชจ๋ธ

      • IE 8 ์ดํ•˜์™€ ํ˜ธํ™˜ ์•ˆ๋จ

      • ๊ธฐ์ˆ ์ ์œผ๋กœ ๋ถ€์กฑ

      • DOM Level 0 event model

    • ํ‘œ์ค€ ์ด๋ฒคํŠธ ๋ชจ๋ธ (Standard event model)

      • ํ˜„์žฌ IE 9 ์ด์ƒ๊ณผ ๋‹ค๋ฅธ ๋ชจ๋“  web browser์—์„œ ์ง€์›

      • DOM Level 2 event model

    • ์ธํ„ฐ๋„ท ์ต์Šคํ”Œ๋กœ๋Ÿฌ ์ด๋ฒคํŠธ ๋ชจ๋ธ (Internet Explorer event model)

      • IE 8 ์ดํ•˜์—์„œ๋งŒ ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ๋ชจ๋ธ

      • ๋‹ค๋ฅธ web browser์—์„œ ์ง€์›ํ•˜์ง€ ์•Š์Œ

      • ๋” ์ด์ƒ ์‚ฌ์šฉ ์•ˆํ•จ

.addEventListener()

: DOM ๊ฐ์ฒด์— event handler ํ•จ์ˆ˜๋ฅผ ์ ์šฉ

  • EventTarget.addEventListener (type, listener, [, useCapture]);

    • type: ์ด๋ฒคํŠธ ์œ ํ˜•

    • listener: ์ด๋ฒคํŠธ ๋ฐœ์ƒ ์‹œ ์‹คํ–‰ํ•  callback ํ•จ์ˆ˜ (event handler)

    • useCapture: ๊ธฐ๋ณธ ๊ฐ’ (false), ์ƒ์œ„ ๋…ธ๋“œ๋กœ ์ „ํŒŒ (bubbling), ๋งŒ์•ฝ true ์ธ ๊ฒฝ์šฐ ํ•˜์œ„ node๋กœ ์ „ํŒŒ (capturing)

preventDefault()

: Event ๊ธฐ๋ณธ ๊ธฐ๋Šฅ ์ž‘๋™์„ ๋ง‰์Œ

.removeEventListener()

: Event handler ์ œ๊ฑฐ

  • ์ง์ด๋˜๋Š” addEventListener() ์™€ ๋˜‘๊ฐ™์€ ์„ธ๊ฐ€์ง€ ์ธ์ž๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ์–ด์•ผํ•จ

Event ์ „ํŒŒ

Event ์ „ํŒŒ์˜ 3๋‹จ๊ณ„

  1. document node์—์„œ event ๋ฐœ์ƒ node๊นŒ์ง€ ๋‚ด๋ ค๊ฐ€๋ฉด์„œ event ์ „ํŒŒ

  2. event ๋ฐœ์ƒ node

  3. event ๋ฐœ์ƒ node์—์„œ document node๊นŒ์ง€ ์˜ฌ๋ผ๊ฐ€๋ฉด์„œ event ์ „ํŒŒ

.stopPropagation()

: ์ด๋ฒคํŠธ ์ „ํŒŒ๋ฅผ ๋ง‰๋Š” ์ด๋ฒคํŠธ API

  • Event๋Š” ํ•ด๋‹น ์š”์†Œ์—์„œ ์ „ํŒŒ๋˜๋ฉฐ, capturing๊ณผ bubbling์œผ๋กœ ๊ตฌ๋ถ„๋œ๋‹ค

  • ํ•ญ์ƒ capturing ๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜์—ฌ bubbling์œผ๋กœ ์ข…๋ฃŒ๋œ๋‹ค

  • addEventListener method์˜ ์„ธ ๋ฒˆ์งธ ์ธ์ž์ธ userCapture (false ๊ฐ€ default)๋ฅผ ํ†ตํ•ด ํŠน์ • ์ƒํ™ฉ์— ๋Œ€ํ•œ ์ด๋ฒคํŠธ ๊ด€๋ฆฌ๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค

Event ๊ฐ์ฒด์™€ this

: Event listener์˜ callback ํ•จ์ˆ˜์—์„œ this๋ฅผ ํ™œ์šฉํ•˜๋Š” ๊ฒฝ์šฐ event listener์— binding ๋˜์–ด ์žˆ๋Š” ์š”์†Œ๊ฐ€ ์ง€์ •๋œ๋‹ค

this์™€ target

  • Event handler๊ฐ€ ํ˜ธ์ถœํ•˜๋Š” ํ•จ์ˆ˜์˜ this์˜ ์—ญํ• 

    : ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•œ ๊ฐ์ฒด

  • event.target == this

Last updated