Search

์ด๋ฒคํŠธ

์ด๋ฒคํŠธ

์ •์˜

์–ด๋–ค ์‚ฌ๊ฑด์ด ๋ฐœ์ƒํ–ˆ์Œ์„ ๋‚˜ํƒ€๋‚ด๋Š” ์‹ ํ˜ธ
Node.js์—์„œ ์ด๋ฒคํŠธ๋Š” ์ด๋ฒคํŠธ ๊ธฐ๋ฐ˜ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ๋ชจ๋ธ์„ ํ†ตํ•ด ์ฒ˜๋ฆฌ๋ฉ๋‹ˆ๋‹ค. ์ด ๋ชจ๋ธ์€ ์ด๋ฒคํŠธ ๋ฐœ์ƒ์ž(Event Emitter)์™€ ์ด๋ฒคํŠธ ๋ฆฌ์Šค๋„ˆ(Event Listener) ๊ฐ„์˜ ์ƒํ˜ธ ์ž‘์šฉ์œผ๋กœ ๊ตฌ์„ฑ๋ฉ๋‹ˆ๋‹ค. ์ด๋ฒคํŠธ ๋ฐœ์ƒ์ž๋Š” ํŠน์ • ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Œ์„ ์•Œ๋ฆฌ๊ณ , ์ด๋ฅผ ๋“ฃ๊ณ  ์žˆ๋Š” ์ด๋ฒคํŠธ ๋ฆฌ์Šค๋„ˆ๋Š” ํ•ด๋‹น ์ด๋ฒคํŠธ์— ๋Œ€ํ•œ ํ–‰๋™์„ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค.

๋ฌธ๋ฒ•

Node.js์˜ events ๋ชจ๋“ˆ์„ ์‚ฌ์šฉํ•˜์—ฌ ์ด๋ฒคํŠธ๋ฅผ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ฃผ์š” ๋ฉ”์†Œ๋“œ๋กœ๋Š” on, emit, once ๋“ฑ์ด ์žˆ์Šต๋‹ˆ๋‹ค.
const EventEmitter = require('events');
JavaScript
๋ณต์‚ฌ

์ฃผ์š” ๊ฐ์ฒด ๋ฐ ๋ฉ”์†Œ๋“œ

๊ฐ์ฒด ๋ฐ ์†์„ฑ
์„ค๋ช…
EventEmitter
events ๋ชจ๋“ˆ์—์„œ ์ œ๊ณตํ•˜๋Š” ํด๋ž˜์Šค๋กœ, ์ด๋ฒคํŠธ ๊ธฐ๋ฐ˜ ํ”„๋กœ๊ทธ๋ž˜๋ฐ์„ ์œ„ํ•œ ํ•ต์‹ฌ ์—ญํ• ์„ ๋‹ด๋‹นํ•ฉ๋‹ˆ๋‹ค.
on(event, listener)
์ง€์ •๋œ ์ด๋ฒคํŠธ์— ๋Œ€ํ•œ ๋ฆฌ์Šค๋„ˆ๋ฅผ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค.
once(event, listener)
์ง€์ •๋œ ์ด๋ฒคํŠธ์— ๋Œ€ํ•œ ๋ฆฌ์Šค๋„ˆ๋ฅผ ํ•œ ๋ฒˆ๋งŒ ์‹คํ–‰ํ•˜๋„๋ก ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค.
removeListener(event, listener)
์ด๋ฒคํŠธ์— ๋Œ€ํ•œ ํŠน์ • ๋ฆฌ์Šค๋„ˆ๋ฅผ ์ œ๊ฑฐํ•ฉ๋‹ˆ๋‹ค.
removeAllListeners([event])
๋ชจ๋“  ์ด๋ฒคํŠธ ๋ฆฌ์Šค๋„ˆ ๋˜๋Š” ํŠน์ • ์ด๋ฒคํŠธ์˜ ๋ชจ๋“  ๋ฆฌ์Šค๋„ˆ๋ฅผ ์ œ๊ฑฐํ•ฉ๋‹ˆ๋‹ค.
setMaxListeners(n)
์ด๋ฒคํŠธ์— ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ ๋ฆฌ์Šค๋„ˆ ์ˆ˜๋ฅผ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค.
getMaxListeners()
ํ˜„์žฌ ์ด๋ฒคํŠธ์— ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ ๋ฆฌ์Šค๋„ˆ ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
listeners(event)
์ง€์ •๋œ ์ด๋ฒคํŠธ์— ๋Œ€ํ•œ ๋ฆฌ์Šค๋„ˆ ๋ฐฐ์—ด์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
emit(event[, arg1][, arg2][, ...])
์ง€์ •๋œ ์ด๋ฒคํŠธ๋ฅผ ๋ฐœ์ƒ์‹œํ‚ค๊ณ , ๊ฐ ๋ฆฌ์Šค๋„ˆ์—๊ฒŒ ์ „๋‹ฌํ•  ์ธ์ˆ˜๋ฅผ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค.

์˜ˆ์‹œ์ฝ”๋“œ

const EventEmitter = require('events'); // ์ด๋ฒคํŠธ ๋ฐœ์ƒ์ž ์ƒ์„ฑ const myEmitter = new EventEmitter(); // ์ด๋ฒคํŠธ ๋ฆฌ์Šค๋„ˆ ๋“ฑ๋ก myEmitter.on('event', (arg) => { console.log('์ด๋ฒคํŠธ ๋ฐœ์ƒ:', arg); }); // ์ด๋ฒคํŠธ ๋ฐœ์ƒ myEmitter.emit('event', '๋งค๊ฐœ๋ณ€์ˆ˜ ์ „๋‹ฌ');
JavaScript
๋ณต์‚ฌ
const EventEmitter = require('events'); const myEvent = new EventEmitter(); myEvent.addListener('event1', () => { console.log('์ด๋ฒคํŠธ 1'); }); myEvent.on('event2', () => { console.log('์ด๋ฒคํŠธ 2'); }); myEvent.on('event2', () => { console.log('์ด๋ฒคํŠธ 2 ์ถ”๊ฐ€'); }); myEvent.once('event3', () => { console.log('์ด๋ฒคํŠธ 3'); }); // ํ•œ ๋ฒˆ๋งŒ ์‹คํ–‰๋จ myEvent.emit('event1'); // ์ด๋ฒคํŠธ ํ˜ธ์ถœ myEvent.emit('event2'); // ์ด๋ฒคํŠธ ํ˜ธ์ถœ myEvent.emit('event3'); myEvent.emit('event3'); // ์‹คํ–‰ ์•ˆ ๋จ myEvent.on('event4', () => { console.log('์ด๋ฒคํŠธ 4'); }); myEvent.removeAllListeners('event4'); myEvent.emit('event4'); // ์‹คํ–‰ ์•ˆ ๋จ const listener = () => { console.log('์ด๋ฒคํŠธ 5'); }; myEvent.on('event5', listener); myEvent.removeListener('event5', listener); myEvent.emit('event5'); // ์‹คํ–‰ ์•ˆ ๋จ console.log(myEvent.listenerCount('event2'));
JavaScript
๋ณต์‚ฌ