Unique Custom Event
- ๋ฅ์ง
- Development
- ๋ถ๋ฅ
- Javascript
- ๋ฑ๋ก์ผ
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');
์ ์ญ์์ ํค๋ณด๋๋ ์๋์ฐ ๋ฆฌ์ฌ์ด์ฆ, ์คํฌ๋กค๊ฐ์ ์ผ์ ์ฌ์ฉํ๋ ์ด๋ฒคํธ๋ฅผ ์ฌ์ฉํ ๋ ์ด ๋๊ตฌ๊ฐ ๋ง์ ๋์์ด ๋์ด์ ํญ์ ์ฌ์ฉํ๊ณค ํ๋ค.
0๊ฐ์ ๋๊ธ
๋ฑ๋ก๋ ๋๊ธ์ด ์์ต๋๋ค.