Difference between Events and Functions?

前端 未结 3 1952
情深已故
情深已故 2021-01-05 03:42

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

相关标签:
3条回答
  • 2021-01-05 04:22

    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(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.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.

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

    0 讨论(0)
  • 2021-01-05 04:26

    An event is an identifier used within tools (.on(), .emit() etc) to set and execute callbacks. Functions are reusable code.

    0 讨论(0)
  • 2021-01-05 04:31

    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.

    They are such a pain to debug though that I'd much rather just use functions.

    0 讨论(0)
提交回复
热议问题