CustomEvent

๐Ÿ™„ ๊ฒฝํ—˜

Vue๊ณต๋ถ€์ค‘, Component๋ถ€๋ถ„์—์„œ ๋ถ€๋ชจ์™€ ์ž์‹Component๊ฐ„์˜ ์†Œํ†ต์„ ๋ณด๊ณ ์žˆ์—ˆ๋‹ค.
React๋ฅผ ์ด๋ฏธ ์•Œ๊ณ  ์žˆ์—ˆ๊ธฐ ๋•Œ๋ฌธ์— ์†์„ฑ์„ ์ „๋‹ฌํ•˜๊ณ , ์†์„ฑ์œผ๋กœ ์ „๋‹ฌ๋œ ๋ถ€๋ชจ์˜ ์ด๋ฒคํŠธ๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๊ตฌ์กฐ๋ž‘ ๋น„์Šทํ•œ๊ฒƒ ๊ฐ™์•„ ๋ฌธ์ œ๋Š” ์—†์—ˆ๋‹ค.
๊ทธ๋Ÿฐ๋ฐ.. dispatchEvent๋ผ๋Š” ๋ฉ”์†Œ๋“œ๋ฅผ ์ฒ˜์Œ๋ณด๊ฒŒ๋˜์—ˆ๋‹ค.

๐Ÿค” ์˜๋ฌธ

Redux์ƒํƒœ๊ด€๋ฆฌ๋ฅผ ํ•  ๋•Œ, ์ œ๊ณต๋˜๋Š” dispatch๋ฉ”์†Œ๋“œ๋ฅผ ํ™œ์šฉํ•˜์—ฌ state์˜ ๋ณ€๊ฒฝ์‹œ์ผฐ๋Š”๋ฐ ๋น„์Šทํ•œ๊ฑด๊ฐ€?

๐Ÿ˜† ์ปค์Šคํ…€ ์ด๋ฒคํŠธ ์ƒ์„ฑ ๋ฐ ํ˜ธ์ถœ(?)!

์‹คํ–‰์˜ˆ์ œ

๋ˆ„๊ฐ€ ๋Œ€์‹  ์‹คํ–‰ํ•ด์ค˜

HTML

<div class="event1">๋ˆ„๊ฐ€ ๋Œ€์‹  ์‹คํ–‰ํ•ด์ค˜</div>
<button class="support">๋Œ€์‹ ์‹คํ–‰</button>

JavaScript

const event = new CustomEvent('test', {
  detail: '์‚ฌ์šฉ์ž ์ง€์ • ์ด๋ฒคํŠธ ์ž…๋‹ˆ๋‹ค.',
  // ์ปค์Šคํ…€์ด๋ฒคํŠธ ๋“ฑ๋ก ๋ฐ, ๋‘๋ฒˆ์งธ ์ธ์ž๋กœ data ์„ค์ • ๊ฐ€๋Šฅ
})
const support = document.querySelector('.support')
const elem1 = document.querySelector('.event1')

elem1.addEventListener('test', e => {
  alert(e.detail)
  // elem1์— ์ปค์Šคํ…€์ด๋ฒคํŠธ 'event' ๋“ฑ๋ก
})
support.addEventListener('click', () => {
  elem1.dispatchEvent(event)
  // elem1์— ๋“ฑ๋ก๋˜์–ด์žˆ๋Š” ์ปค์Šคํ…€์ด๋ฒคํŠธ 'event'๋ฅผ ์‹คํ–‰์‹œ์ผœ์ค˜
})

๐Ÿง๊ฒฐ๋ก 

  • new CustomEvent()๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ, ์‚ฌ์šฉ์ž์ง€์ • ์ด๋ฒคํŠธ๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ์œผ๋ฉฐ, ๋ฐ์ดํ„ฐ๊ฐ’๋„ ๋„ฃ์–ด์ค„ ์ˆ˜ ์žˆ๋‹ค.
  • ํ•ด๋‹น ์ด๋ฒคํŠธ๊ฐ€ ์—ฐ๊ฒฐ๋œ ์—˜๋ฆฌ๋จผํŠธ์— ์ง์ ‘์ ์œผ๋กœ ์‚ฌ์šฉ์ž์˜ ์š”์ฒญ? ํ˜ธ์ถœ? ์ด ๊ฐ€์ง€ ์•Š๋”๋ผ๋„ ์—˜๋ฆฌ๋จผํŠธ.dispatchEvent(์ด๋ฒคํŠธ๋ช…)๋ฅผ ํ†ตํ•ด, ์‹คํ–‰์‹œํ‚ฌ ์ˆ˜ ์žˆ๋‹ค.

@SangMin
๐Ÿ‘† H'e'story

๐Ÿš€GitHub