ข้ามไปยังเนื้อหา

EventEmitter

EventEmitter (จาก node:events) คือ class ที่ขับเคลื่อน I/O object เกือบทุกตัวใน Node.js HTTP server, TCP sockets, file streams, child processes และ library ของ third-party หลายตัวล้วน extend EventEmitter การเข้าใจ class นี้หมายถึงการเข้าใจวิธีที่ Node สื่อสารระหว่าง components

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

once ลงทะเบียน listener ที่ลบตัวเองออกอัตโนมัติหลังจาก emission ครั้งแรก

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

Extend EventEmitter เพื่อให้ class ของคุณมีความสามารถ event-driven

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

off คือ alias ของ removeListener ที่เพิ่มมาใน Node 10 listenerCount ให้คุณตรวจสอบว่ามี listeners กี่ตัวที่ลงทะเบียนสำหรับ event หนึ่งๆ — มีประโยชน์สำหรับตรวจจับ memory leaks ที่อาจเกิดขึ้น

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

ความแตกต่างหลักระหว่าง emitter.on() และ emitter.once() คืออะไร?
EventEmitter listener ทำงานเมื่อไหร่เทียบกับ emitter.emit()?
Node.js built-in class ใดบ้างที่ extend EventEmitter?