以下代码来自http://www.tutorialspoint.com/nodejs/nodejs_event_loop.htm。在该代码中,data_received事件在connectHandler()函数的定义中触发。虽然未调用connectHandler()函数,但会触发data_received事件。怎么可能?
// Import events module
var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();
// Create an event handler as follows
var connectHandler = function connected() {
console.log('connection succesful.');
// Fire the data_received event
eventEmitter.emit('data_received');
}
// Bind the connection event with the handler
eventEmitter.on('connection', connectHandler);
// 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.");
输出:
connection succesful.
data received succesfully.
Program Ended.
答案 0 :(得分:1)
// Fire the connection event
eventEmitter.emit('connection');
在这里你应该观察到一个'connection'事件被触发,它被绑定到connectHandler函数,从而调用更多的事件。