window ๊ฐ™์ด ์ „์—ญ์—์„œ ์‚ฌ์šฉํ•˜๋Š” ์ด๋ฒคํŠธ๋ฅผ ์—ฌ๋Ÿฌ๊ตฐ๋ฐ์—์„œ ์ถ”๊ฐ€ํ•˜๋ฉด ์„œ๋กœ ์ค‘๋ณต๋˜์–ด์„œ ๊ผฌ์—ฌ๋ฒ„๋ฆฐ๋‹ค.
๊ทธ๋ž˜์„œ ๋…๋ฆฝ์ ์œผ๋กœ ์‚ฌ์šฉํ•˜๊ณ  ๊ด€๋ฆฌํ•˜๊ณ  ์‹ถ์„๋•Œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค.

/**
 * initial custom event
 * ์ค‘๋ณต๋˜๋Š” `dom`์—๋‹ค ์—ฌ๋Ÿฌ ์ด๋ฒคํŠธ๋ฅผ ๋„ฃ๊ณ  ์‹ถ์„๋•Œ(ํŠนํžˆ window) ์œ ๋‹ˆํฌํ•œ ์ด๋ฆ„์œผ๋กœ ์ด๋ฒคํŠธ๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋„๋ก ์ปค์Šคํ…€ ์ด๋ฒคํŠธ๋ฅผ ๋งŒ๋“ค์–ด์„œ ์‚ฌ์šฉํ• ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.
 * https://gist.github.com/yairEO/cb60592476a4204b27e83048949dbb45
 */
export function initCustomEvent()
{
  const events = {
    on(event, cb, opts)
    {
      if (!this.namespaces) this.namespaces = {};
      // ์ค‘๋ณต๋œ ์ด๋ฒคํŠธ๊ฐ€ ์„ค์ •ํ•œ๋‹ค๋ฉด ์ด์ „ ์ด๋ฒคํŠธ๋ฅผ ์‚ญ์ œํ•œ๋‹ค.
      if (this.namespaces[event]) this.off(event);
      this.namespaces[event] = cb;
      const options = opts || false;
      this.addEventListener(event.split('.')[0], cb, options);
      return this;
    },
    off(event)
    {
      if (!this.namespaces[event]) return;
      this.removeEventListener(event.split('.')[0], this.namespaces[event]);
      delete this.namespaces[event];
      return this;
    },
  };
  window.on = document.on = Element.prototype.on = events.on;
  window.off = document.off = Element.prototype.off = events.off;
}

์ด์™€๊ฐ™์€ ํ•จ์ˆ˜๋ฅผ ๋จผ์ € ์‹คํ–‰ํ•˜๊ณ  ๋‹ค์Œ๊ณผ ๊ฐ™์ด on()๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ด๋ฒคํŠธ๋ฅผ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค.

window.on('click.foo', () => { console.log('click.foo'); });
window.on('click.bar', () => { console.log('click.bar'); });

์ด๋ฒคํŠธ๋ฅผ ์‚ญ์ œํ•˜๋ ค๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด off()๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

window.off('click.foo');
window.off('click.bar');

์ „์—ญ์—์„œ ํ‚ค๋ณด๋“œ๋‚˜ ์œˆ๋„์šฐ ๋ฆฌ์‚ฌ์ด์ฆˆ, ์Šคํฌ๋กค๊ฐ™์€ ์ผ์„ ์‚ฌ์šฉํ•˜๋Š” ์ด๋ฒคํŠธ๋ฅผ ์‚ฌ์šฉํ• ๋•Œ ์ด ๋„๊ตฌ๊ฐ€ ๋งŽ์€ ๋„์›€์ด ๋˜์–ด์„œ ํ•ญ์ƒ ์‚ฌ์šฉํ•˜๊ณค ํ•œ๋‹ค.

๋ฉ”ํƒ€๋ฐ์ดํ„ฐ

์กฐํšŒ์ˆ˜
573
์ข‹์•„์š”
0

0๊ฐœ์˜ ๋Œ“๊ธ€

๋“ฑ๋ก๋œ ๋Œ“๊ธ€์ด ์—†์Šต๋‹ˆ๋‹ค.