核心知识点:
Node.js有多个内置事件,可以通过引入events模块,并实例化EventEmitter来绑定、监听事件
var events = require('events'); // 引入 events 模块
var eventEmitter = new events.EventEmitter(); // 创建EventEmitter 对象
eventEmitter.on("data_received",function(){ }); // 事件绑定 ,事件的名字为 data_received
eventEmitter.emit('data_received'); // 事件触发
示例代码:
// 引入 events 模块
var event = require("events");
var eventEmitter = new event.EventEmitter();
// 匿名函数绑定 connection 事件
eventEmitter.on("connection",function connected(){
console.log('链接成功');
// 触发 data_received 事件
eventEmitter.emit('data_received');
});
// 匿名函数绑定 data_received 事件
eventEmitter.on("data_received",function(){
console.log('数据链接成功');
});
// 触发 connection 事件
eventEmitter.emit("connection");
console.log('程序执行结束');