Node.js EventEmitter 功能

學習JS 搭配 NODE的監聽行為來須觸發功能

你可以想像將文件打開這個動作可以用來觸發一些指定行為。

// 導入 events 模塊
var events = require('events');
// 創立 eventEmitter 對象
var eventEmitter = new events.EventEmitter();

下面的實例一就是透過一對一的監聽來觸發活動

let events = require('events');
//導入event功能

let listenerCallback = (data) => {
    console.log('Celebrate ' + data);
}
//建立功能listenerCallback 

let doSomething = (data) => {
  console.log('fo '+ data);
}
//建立功能listenerCallback2

let myEmitter = new events.EventEmitter();
//創立events.EventEmitter()
let myEmitter2 = new events.EventEmitter();
//創立events.EventEmitter()

myEmitter2.on('3',doSomething)
//建立監聽
myEmitter.on('celebration',listenerCallback)
//建立監聽
myEmitter.emit('celebration','good times, come on!')

myEmitter2.emit('3','good times, come on!')