node 中的 EventEmitter 类提供了监听事件的方法 on(event, listener) 和 触发事件的方法 emit(event, [arg1], [arg2], […])
emit触发信号之后,on监听到事件后程序是如何执行的呢?
var events = require("events");
var eventEmitter = new events.EventEmitter();
var connectHandler = function (){
console.log("data_received");
eventEmitter.emit("data_received");
}
eventEmitter.on("data_received",function(){
console.log("data_receive ---> connection");
eventEmitter.emit("connection");
});
eventEmitter.on("connection",function(){
console.log(" connection ---> test");
eventEmitter.emit("test");
});
eventEmitter.on("test",function(){
console.log("I have listened test");
});
connectHandler();
console.log("end");
上面的代码中有三个 on() 监听事件,其中两个的回调函数内又有新的 emit()。 若按照上面代码的顺序进行执行,console中的结果是
data_received
data_receive ---> connection
connection ---> test
I have listened test
end
但是如果将connectHandler中和 on中的console.log 和 emit调换顺序的话,运行会得到相反的结果:
var events = require("events");
var eventEmitter = new events.EventEmitter();
var connectHandler = function (){
eventEmitter.emit("data_received");
console.log("data_received");
}
eventEmitter.on("data_received",function(){
eventEmitter.emit("connection");
console.log("data_receive ---> connection");
});
eventEmitter.on("connection",function(){
eventEmitter.emit("test");
console.log(" connection ---> test");
});
eventEmitter.on("test",function(){
console.log("I have listened test");
});
connectHandler();
console.log("end");
I have listened test
connection ---> test
data_receive ---> connection
data_received
end
这个结果说明,在emit触发事件之后,会先寻找是否存在对应的事件监听,如果有优先执行其回调函数,执行完毕后才会返回值。