EventTarget.addEventListener()
target.addEventListener(type, listener[, options]);
์๊ฐ
1. EventTarget์ ๋ฉ์๋์ด๋ค.
2. ์ฃผ์ด์ง ์ด๋ฒคํธ ์ ํ์, EventListener๋ฅผ ๊ตฌํํ ํจ์๋ฅผ ์ด๋ฒคํธ ์ฒ๋ฆฌ๊ธฐ ๋ชฉ๋ก์ ์ถ๊ฐํด ์๋ํ๋ค.
3. EventTarget์ ๋ณดํต Element, Document, Window์ง๋ง, XMLHttpRequest์ ๊ฐ์ด ์ด๋ฒคํธ๋ฅผ ์ง์ํ๋ ๋ชจ๋ ๊ฐ์ฒด๋ฅผ ๋์์ผ๋ก ์ง์ ํ ์ ์๋ค.
๋งค๊ฐ๋ณ์
e.target ๊ณผ ๊ฐ์ด ์ด๋ฒคํธ ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐํ๊ณ ์ถ์ ๊ฒฝ์ฐ ์๋๋ฅผ ์ฌ์ฉํ๋ค.
target.addEventListener('click',(e)=>{
console.log(e);
console.log('callback test');
});
์ฌ์ฉ ์์) 1. ํจ์ ์์์ ์ด๋ฒคํธ๋ฆฌ์ค๋ ๋ฑ๋ก
๋ฒํผ์ ๋๋ฅด๋ฉด ๋ฒํผ๋ค์ด ๋ณด์ด๋๋ก, ๊ทธ๋ฆฌ๊ณ ๊ทธ ๋ฒํผ๋ค์ eventListener์์ฑ์ ๊ฐ๋๋ก ํ๋ค.
<button type="button">Button Appear</button>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
const divs =[ ...document.getElementsByTagName('div')]
const appearBtn = document.getElementsByTagName('button')[0];
appearBtn.addEventListener('click',makeBtn)
function makeBtn(){
divs.forEach(elem => {
const btn = document.createElement('button');
btn.textContent = 'Example' ;
btn.addEventListener('click',(e)=>{
console.log('callback test');
})
elem.appendChild(btn);
});
}
์ฌ์ฉ ์์) 2. ์ฝ๋ฐฑํจ์์ ๊ฐ์ ์ ๋ฌํ๊ณ ์ถ์ ๋(์ต๋ช ํจ์)
const edit = document.createElement('button');
edit.addEventListener('click',() => editComment(user_id,comment_id));
const remove = document.createElement('button');
remove.addEventListener('click',()=> removeComment(user_id,comment_id));
์ฝ๋ฐฑํจ์์ ๊ฐ์ ์ ๋ฌํ๊ธฐ ์ํด ์ต๋ช ํจ์๋ฅผ ๋ง๋ค๊ณ , ๊ทธ ์์์ ์ง์ญ๋ณ์๋ฅผ ์ธ์๋ก ๋ฐ์ ํจ์๋ฅผ ์คํ์ํจ๋ค.
ํด๋ฆญ ์ด๋ฒคํธ๊ฐ ๋ฐ์ํ์ ๋, ์ต๋ช ํ์ดํ ํจ์๊ฐ ์คํ๋๋ฉด์ ์ต๋ช ํจ์ ์์์๋ ์ฝ๋๋ ๊ฐ์ด ์คํ๋๊ธฐ ๋๋ฌธ์ ์ํ๋ ๊ฒฐ๊ณผ๋ฅผ ์ป์ ์ ์๋ค.
์ฌ์ฉ ์์) 3. ์ฝ๋ฐฑํจ์์ ๊ฐ์ ์ ๋ฌํ๊ณ ์ถ์ ๋(ํด๋ก์ )
const edit = document.createElement('button');
edit.addEventListener('click',editComment(user_id,comment_id));
function editComment(user_id,comment_id) {
return async function(){
...
try {
await axios.patch(`/comments/${comment_id}`, { comment: newComment });
...
} catch (err) {
console.error(err);
}
}}
- ํจ์ ์คํํํ๋ฅผ ์ธ์๋ก ๋๊ธฐ๊ณ , ์คํํ๋ ํจ์์์ ๋ด๋ถํจ์๋ฅผ ๋ฐํํ๋ ํ์์ด๋ค.
- ํจ์๋ฅผ ๋ฐํํ๋ ์ฝ๋ฐฑํจ์๋ฅผ ์ ๋ฌํ ๊ฒ์ด๋ ๋ค๋ฆ์๋ค.
- editComment(user_id,comment_id) ๋ฅผ ์คํํ๊ณ ๋ฐํ๊ฐ์ธ async function(){..} ์ด ์ฝ๋ฐฑํจ์๋ก ๋ฑ๋ก๋๋ค.
์ ๋ฆฌ) ์ฝ๋ฐฑํจ์๋ ์คํ ๊ฐ๋ฅํ ํจ์ ํํ๋ก ๋๊ฒจ์ฃผ๋ ๊ฒ์ด์ง, ์คํ์ํจ ํํ๋ฅผ ์ ๋ฌํ๋๊ฒ์ ์๋๋ค.
document
.querySelector('.classBtn')
.addEventListener('click', addScript('class'));
- ์์ ๊ฐ์ ์ฝ๋๋ ํด๋ฆญ ์ด๋ฒคํธ๊ฐ ๋ฐ์ํ์ ๋ ์คํ๋๋ ๊ฒ์ด ์๋๋ผ, ์๋ฐ์คํฌ๋ฆฝํธ๊ฐ ์ฝ๋๋ฅผ ํ์ค ํ์ค ์ฝ์ผ๋ฉด์ ์ฆ์ ์คํํด๋ฒ๋ฆฐ๋ค.
- ํด๋ฆญ์ ์ฝ๋ฐฑํจ์๋ก ๋์ํ์ง ์๊ณ ์ ์๋น์ด์ ์ฝ๋ฐฑํจ์๋ ์๋๋ค. ํจ์๋ฅผ ์คํ์ํจ ํํ๊ธฐ ๋๋ฌธ์ด๋ค.
Reference
1. https://developer.mozilla.org/ko/docs/Web/API/EventTarget/addEventListener
'๐ Front > ๐ฑ Vanilla JS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Iterable VS Enumerable] ๊น๋ํ๊ฒ ์ ๋ฆฌํ๊ณ ๊ฐ์๋ค (0) | 2021.11.19 |
---|---|
arguments ๊ฐ์ฒด: function์์ ์๋ ๋, ๋๊ฐ ์ ์ธํ๋? (0) | 2021.11.18 |
key์ ์ ๊ทผํ๋ 2๊ฐ์ง ๋ฐฉ๋ฒ. obj.key, obj['key'] (0) | 2021.08.03 |
Window ๊ฐ์ฒด (0) | 2021.02.23 |
ES(ECMAScript) VS JS(JavaScripit) ์ฐจ์ด์ (0) | 2021.02.13 |