Node.js使用大量事件,這也是爲什麼Node.js相對於其他類似技術比較快的原因之一。當Node啓動其服務器,就可以簡單地初始化其變量,聲明函數,然後等待事件的發生。
雖然事件似乎類似於回調。不同之處在於當回調函數被調用異步函數返回結果,其中的事件處理工作在觀察者模式。監聽事件函數作爲觀察者。每當一個事件被解僱,其監聽函數開始執行。Node.js有多個內置的事件。 主要扮演者是 EventEmitter,可使用以下語法導入。
var events = require('events');//添加事件模塊的引用
//create an eventEmitter object創建事件發射器對象
var eventEmitter = new events.EventEmitter();
//create a function connected which is to be executed
//when 'connection' event occurs
//創建一個連接的要執行的函數
//“connection”事件發生時
var connected = function connected() {
console.log('connection succesful.');
// fire the data_received event 啓動數據接收事件
eventEmitter.emit('data_received');
}
// bind the connection event with the connected function將連接事件與連接的函數綁定
eventEmitter.on('connection', connected);
// bind the data_received event with the anonymous function
eventEmitter.on('data_received', function(){
console.log('data received succesfully.');
});
// fire the connection event
eventEmitter.emit('connection');
console.log("Program Ended.");//
eventEmitter.on('connection', connected);將連接事件connection與 connected函數綁定,當執行eventEmitter.emit('connection');的時候觸發事件執行與之對應的函數