事件和功能之间的区别? [英] Difference between Events and Functions?

查看:148
本文介绍了事件和功能之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Node的新手,我正在努力了解事件和函数之间的主要区别。两者都需要被触发,所以为什么无论如何都必须要触发事件?

I am new to Node, and I am struggling to understand the main difference between Events and Functions. Both need to be triggered, so why do we need an Event at all if we have to trigger it anyway?

与触发函数有何不同?

How is it different than having a Function triggered?

示例代码:

var events = require('events');
var eventEmitter = new events.EventEmitter();

eventEmitter.on('event1', function () {
    console.log('Event 1 executed.');
    eventEmitter.emit('event2');
});

eventEmitter.on('event2', function() {
    console.log('Event 2 executed.');
});

eventEmitter.emit('event1');
console.log('Program Ended.');

我们可以通过函数实现相同的结果,对吧?

We can achieve the same result by functions, right?

我确信这在Node中具有重要意义(否则它将不存在,大声笑),但是我正在努力理解它。

I am sure this has some serious importance in Node (otherwise it would not exist, lol), but I am struggling to understand it.

帮助表示赞赏! :)

推荐答案

事件处理异步操作。从功能上讲,它们并不是真正可互换的。

Events deal with asynchronous operations. They aren't really related to functions in the sense that they are interchangeable.

eventEmitter.on 本身就是一个函数,它使用两个参数作为事件名称,然后在事件发生时执行一个函数(回调)。

eventEmitter.on is itself a function, it takes two arguments the event name, then a function (callback) to be executed when the event happens.

eventEmitter.on(evt ,回调)

无法告知事件何时发出,因此您提供了一个在事件发生时执行的回调

There is no way to tell WHEN the event will be emitted, so you provide a callback to be executed when the event occurs.

在您的示例中,您将控制事件的触发时间,这与实际使用情况不同,在现实世界中,您可能需要服务器侦听可以随时连接的连接

In your examples, you are controlling when the events are triggered, which is different than real world use where you may have a server listening for connections that could connect at anytime.

server.listen('9000', function(){
    console.log('Server started');
});

server.on('connection', function(client){
    console.log('New client connected');
    doSomethingWithClient(client);
});

//series of synchronous events
function doSomethingWithClient(client){
    //something with client
}

对于 server.listen ,一旦调用就绪,服务器不会立即启动

For server.listen the server doesn't start immediately, once its ready the callback is called

server.on('connection')侦听客户端连接,它们可以随时出现。然后,在发生连接时触发该事件,导致运行回调。

server.on('connection') listens for client connections, they can come at any time. The event is then triggered when a connection occurs, causing the callback to be run.

然后有 doSomethingWithClient 只是与客户端连接发生时要执行的一组同步操作有关的功能。

Then there is doSomethingWithClient this is just a function with a set of synchronous operations to be done when a client connection occurs.

这篇关于事件和功能之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆