250x250
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 | 31 |
Tags
- 삶
- error
- API
- CLASS
- JavaScript
- hardhat
- Ethereum
- CSS
- bitcoin
- SSR
- express.js
- web
- nextJS
- REACT
- typeScript
- evm
- HTML
- Interface
- useState
- middleware
- Redux
- tailwindcss
- Props
- graphQL
- 기준
- concept
- blockchain
- built in object
- solidity
- node.js
Archives
- Today
- Total
ReasonJun
javascript : event ( add, remove, dispatch, custom event) 본문
Frontend/Javasciprt
javascript : event ( add, remove, dispatch, custom event)
ReasonJun 2023. 6. 8. 18:22728x90
add / remove
//? .addEventListener()
// Registers to listen for events on the target.
// When an event specified in the target occurs, the specified function is called.
const parentEl = document.querySelector('.parent');
const childEl = document.querySelector('.child');
parentEl.addEventListener('cilck', () => {
console.log('Parent');
});
childEl.addEventListener('cilck', () => {
console.log('Child');
});
//? .removeEventListener()
// Removes the event listener registered on the target.
// It may be necessary to remove events registered for memory management.
// If you're going to remove it, it's a good idea to make it a function name that you can refer to.
const handler = () => {
console.log('Parent!');
};
parentEl.addEventListener('click', handler);
childEl.addEventListener('click', () => {
parentEl.removeEventListener('click', handler);
});
custom event / dispatch
//? dispatch
const child1 = document.querySelector('.child:nth-child(1)');
const child2 = document.querySelector('.child:nth-child(2)');
child1.addEventListener('click', (event) => {
// force an event
child2.dispatchEvent(new Event('click'));
child2.dispatchEvent(new Event('wheele'));
child2.dispatchEvent(new Event('keydown'));
});
child2.addEventListener('click', (event) => {
console.log('Child2 Click');
});
child2.addEventListener('wheel', (event) => {
console.log('Child2 wheel');
});
child2.addEventListener('keydown', (event) => {
console.log('Child2 keydown');
});
//? custom event
child1.addEventListener('hello-world', (event) => {
console.log('fire custom event');
console.log(event.detail); // 123
});
child2.addEventListener('click', () => {
child1.addEventListener(
new CustomEvent('hello-world', {
detail: 123, // Data can be passed only through the 'detail' attribute.
})
);
});
728x90
'Frontend > Javasciprt' 카테고리의 다른 글
javascript : event (event obj, focus form event) (0) | 2023.06.09 |
---|---|
javascript : event (delegation, event bubbling) (0) | 2023.06.08 |
javascript : ecma 2023 updates (0) | 2023.06.08 |
javascript : Array methods that do not mutate the original array (0) | 2023.06.08 |
javascript : Array methods that mutate the original array (0) | 2023.06.08 |
Comments