Event
들어가며
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events
Introduction to events - Learn web development | MDN
Events are actions or occurrences that happen in the system you are programming, which the system tells you about so you can respond to them in some way if desired. For example, if the user selects a button on a webpage, you might want to respond to that a
developer.mozilla.org
이벤트에 대한 정확한 이해가 필요하여 MDN 문서를 읽고 몰랐던 점 & 기억하고 싶은 점을 정리해본다.
A Series of fortunate events
- In the case of the Web, events are fired inside the browser window, and tend to be attached to a specific item that resides in it
- event handler runs when the event fires
- Event handlers are sometimes called event listeners
- 엄밀히 말하면 handler 랑 listner는 다르다. listner가 이벤트를 캐치해서 handler를 run하는 것.
- 같은 JS환경이라도 web과 node에서 이벤트 핸들링 과정이 약간 다르다.
Ways of using web events
- 인라인 이벤트핸들러는 쓰지 말자. 프로퍼티 개념으로 쓰는 것이 좋다.
- 유지보수측면에서 일단 좋고, 자바스크립트와 HTML코드를 분리하는 것이 좋기 때문이다.
//Wrong
const btn = <button onclick="bgChange()">Press me</button>
function bgChange() {
const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
document.body.style.backgroundColor = rndCol;
}
//Right
const btn = document.querySelector('button');
function bgChange() {
const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
document.body.style.backgroundColor = rndCol;
}
btn.onclick = bgChange;
- document.querySelector로 요소를 가져오고 그 요소의 이벤트프로퍼티에 바인딩을 하는 방법이 있고,
- 그 요소에 addEventListner로 이벤트 핸들러를 추가할 수 있다.
- addEventListner의 이점(property로 부여하는 방식에 비해)은 여러 가지 이벤트에 대해 핸들러를 부여할 수 있다는 점과, removeEventListner를 사용할 수 있다는 점이다.
Other event concepts
- 콜백에는 보통 이벤트 객체가 넘어간다.
- 이벤트 객체에 있는 event.target 자체는 html요소(버튼 등)을 가리킨다.
- 그 안의 innerHTML은 텍스트를 가리킨다.
- document.querySelector는 제일 첫 요소를, querySelectorAll은 해당하는 배열 전체를 가져온다.
- 버블링은 한 요소에 이벤트가 발생시 그 요소에 할당된 핸들러가 동작하고 부모의 핸들러도 동작하는 것이다.(최상단까지)
- event.target은 이벤트가 시작된 요소이다. 버블링이 진행되어도 변하지 않는다.
- this=event.currentTarget은 현재 실행중인 핸들러가 할당된 요소를 말한다.
- document 객체를 만날때까지 이벤트가 전파되는데, event.stopPropagation을 핸들러로 넣어주면 버블링을 멈출 수 있다.
- 이벤트 자체는 캡처링을 통해 가장안쪽요소까지 전달이 되고, 핸들러는 버블링 순으로 일어난다. 캡처링 이벤트를 잡아내려면 addEventListner에서 true로 옵션을 주어야 한다.
'Study Log' 카테고리의 다른 글
브라우저 공부 (0) | 2021.11.20 |
---|---|
React.js 공식문서 정리 - Hook (0) | 2021.11.18 |
React.js 공식문서 정리 - Advanced Guides (0) | 2021.11.17 |
JavaScript export와 export default 차이 (0) | 2021.11.09 |
React.js 공식문서 정리 - Main Components (0) | 2021.11.08 |
댓글
이 글 공유하기
다른 글
-
React.js 공식문서 정리 - Hook
React.js 공식문서 정리 - Hook
2021.11.18 -
React.js 공식문서 정리 - Advanced Guides
React.js 공식문서 정리 - Advanced Guides
2021.11.17 -
JavaScript export와 export default 차이
JavaScript export와 export default 차이
2021.11.09 -
React.js 공식문서 정리 - Main Components
React.js 공식문서 정리 - Main Components
2021.11.08