简体   繁体   English

事件和函数的区别?

[英]Difference between Events and Functions?

I am new to Node, and I am struggling to understand the main difference between Events and Functions.我是 Node 新手,我很难理解事件和函数之间的主要区别。 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?与触发 Function 有何不同?

Example code:示例代码:

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?我们可以通过函数来达到同样的效果,对吧?

I am sure this has some serious importance in Node (otherwise it would not exist, lol), but I am struggling to understand it.我确信这在 Node 中具有非常重要的意义(否则它将不存在,哈哈),但我很难理解它。

Help appreciated: :)帮助表示赞赏::)

Events deal with asynchronous operations.事件处理异步操作。 They aren't really related to functions in the sense that they are interchangeable.从它们可以互换的意义上说,它们与功能并不真正相关。

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本身就是一个函数,它接受两个参数作为事件名称,然后是一个在事件发生时要执行的函数(回调)。

eventEmitter.on(evt, callback)

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
}

For server.listen the server doesn't start immediately, once its ready the callback is called对于server.listen服务器不会立即启动,一旦准备好回调被调用

server.on('connection') listens for client connections, they can come at any time. server.on('connection')监听客户端连接,它们可以随时到来。 The event is then triggered when a connection occurs, causing the callback to be run.然后在连接发生时触发该事件,从而导致运行回调。

Then there is doSomethingWithClient this is just a function with a set of synchronous operations to be done when a client connection occurs.然后是doSomethingWithClient这只是一个函数,当客户端连接发生时,它会执行一组同步操作。

events useful in webserver code (that is active on port) not in normal scripts, in normal scripts events will behave same as functions because events will be continually active & listening on port for requests as long as port is up so if we use function instead, function will run only once when.js file is ran thus functions cannot capture incoming request and respond.在网络服务器代码中有用的事件(在端口上处于活动状态)不在普通脚本中,在普通脚本中,事件的行为将与函数相同,因为只要端口启动,事件就会持续活动并在端口上侦听请求,所以如果我们使用 function 代替, function 仅在运行 .js 文件时运行一次,因此函数无法捕获传入请求和响应。

Example: in below code if you see output of below function dummy_func() triggered immediately when js file is ran & printed statement ConditionReport: A client Connected: 0 only once as output, but the EventReport: A client Connected: printed only when opened http://localhost:58080 in browser and again in another tab if i open same http://localhost:58080 it printed again EventReport: A client Connected: 3 Example: in below code if you see output of below function dummy_func() triggered immediately when js file is ran & printed statement ConditionReport: A client Connected: 0 only once as output, but the EventReport: A client Connected: printed only when opened http ://localhost:58080 在浏览器中,如果我打开相同的 http://localhost:58080 它再次在另一个选项卡中打印EventReport: A client Connected: 3

 const express = require('express'); const app = express(); const path = require('path'); const PORT = process.env.PORT || 58080; // Load all static html files in the directory, here index.html file open as default at http://localhost:58080/ but to load html like Resume.html we should call complete http://localhost:58080/Resume.html app.use(express.static(path.join(__dirname))); // Configure Port var server_object=app.listen(PORT, () => console.log("Server listening on port " + PORT)); //Possible incomming Events var incomming_events=server_object.eventNames() console.log("\nserver_object:",incomming_events); //On Event var i=0 server_object.on('connection',()=>{ i=i+1 console.log("\nEventReport: A client Connected:",i); }); //Using if condition instead of Event function dummy_func(j){ console.log("\nConditionReport: A client Connected:",j,"\n"); } var j=0 if (incomming_events.includes('connection')){ dummy_func(j) j=j+1 }

OUTPUT: OUTPUT:

stataraju@statara-ltm7wjr Example2 % node index.js

server_object: [ 'request', 'connection', 'listening' ]

ConditionReport: A client Connected: 0 

Server listening on port 58080

EventReport: A client Connected: 1

EventReport: A client Connected: 2

EventReport: A client Connected: 3

An event is an identifier used within tools ( .on() , .emit() etc) to set and execute callbacks.事件是工具( .on().emit()等)中用于设置和执行回调的标识符。 Functions are reusable code.函数是可重用的代码。

I suppose I see the biggest difference I see is that an event emitter could trigger multiple events that are listening, whereas just calling a function only triggers one thing.我想我看到的最大区别是事件发射器可以触发多个正在侦听的事件,而仅调用一个函数只会触发一件事。

So for example, you could have numerous objects in a game that are all waiting for a step event that increments their animation.因此,例如,您可能在游戏中有许多对象都在等待增加其动画的 step 事件。

They are such a pain to debug though that I'd much rather just use functions.尽管我更愿意只使用函数,但它们调试起来非常痛苦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM