โมดูลเหตุการณ์ Node.js

❮ โมดูลในตัว


ตัวอย่าง

สร้างผู้ฟังเหตุการณ์สำหรับเหตุการณ์ที่เรียกว่า "กรี๊ด" จากนั้นกระตุ้นเหตุการณ์:

var events = require('events');
var eventEmitter = new events.EventEmitter();

eventEmitter.on('scream', function() {
console.log('A scream is detected!');
});
eventEmitter.emit('scream');

ความหมายและการใช้งาน

โมดูลเหตุการณ์มีวิธีการทำงานกับเหตุการณ์

ใน Node.js เหตุการณ์ทั้งหมดเป็นตัวอย่างของวัตถุ EventEmitter


ไวยากรณ์

ไวยากรณ์สำหรับการรวมโมดูลเหตุการณ์และการสร้าง EventEmitter ในแอปพลิเคชันของคุณ:

var events = require('events');
var eventEmitter = new events.EventEmitter();

คุณสมบัติ EventEmitter และวิธีการ

Method Description
addListener() Adds the specified listener
defaultMaxListeners Sets the maximum number of listeners allowed for one event. Default is 10
emit() Call all the listeners registered with the specified name
eventNames() Returns an array containing all registered events
getMaxListeners() Returns the maximum number of listeners allowed for one event
listenerCount() Returns the number of listeners with the specified name
listeners() Returns an array of listeners with the specified name
on() Adds the specified listener
once() Adds the specified listener once. When the specified listener has been executed, the listener is removed
prependListener() Adds the specified listener as the first event with the specified name
prependOnceListener() Adds the specified listener as the first event with the specified name, once. When the specified listener has been executed, the listener is removed
removeAllListeners() Removes all listeners with the specified name, or ALL listeners if no name is specified
removeListener() Removes the specified listener with the specified name
setMaxListeners() Sets the maximum number of listeners allowed for one event. Default is 10

❮ โมดูลในตัว