gpt4 book ai didi

javascript - 尽管未显式调用事件处理程序,但为什么会触发 eventemitter

转载 作者:行者123 更新时间:2023-12-03 06:38:43 25 4
gpt4 key购买 nike

以下代码来自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.

最佳答案

// Fire the connection event 
eventEmitter.emit('connection');

在这里,您应该观察到正在触发一个“连接”事件,该事件绑定(bind)到 connectHandler 函数,从而调用更多事件。

关于javascript - 尽管未显式调用事件处理程序,但为什么会触发 eventemitter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38069572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com