简体   繁体   中英

Node.js - emit vs function call

I have been been using EventEmitters in Node and come across certain situations where I can't decide whether to emit values back into the 'EventEmitter object' and have it listen for them, or simply call a function to set the value.

I have created a simple example to explain my point.

The myTimer function simply emits whatever the favourite number is every second. It's value can be changed either through the changenumber function call or on a changenumber event.

var util = require("util");
var events = require("events");
var favNo = 2;

var myTimer = function() {
    var self = this;
    events.EventEmitter.call(this);

    setInterval(function() {
        self.emit('favourite number', favNo);
    }, 1000);

    // on changenumber event, change number
    this.on('changenumber', function (newNo) {
        favNo = newNo;
    });
}

util.inherits(myTimer, events.EventEmitter);

// on function call, change number
myTimer.prototype.changenumber = function(newNo) {
    favNo = newNo;
}
module.exports = myTimer;

This code below uses the myTimer function and listens for it's 'favourite number' event. The favourite number can be set either with the function call or by emitting 'change number' on the myTimer object.

var myTimer = require('./myTimer.js');
var timer = new myTimer();

timer.on("favourite number", function(number) {
    console.log(number);
});

timer.changenumber(102); // change number using function.
timer.emit('changenumber', 102); // change number by emitting number

Both approaches seem to work, however using the emit to send back values seems like it may become hard to follow if the complexity grows. I have been using socket.io in my projects and have seen it basically emits and listens on the same object for both client and server ends, so maybe that's where I have become confused.

Are there any situations where using one method may be more appropriate than the other?

A couple notes that might clear up some confusion:

  • Events are for when things happen. (eg an error has occurred, data is available)

  • Events should be emitted from within the object itself in almost all cases. It doesn't make sense for something outside of the object to call .emit() . Only call .emit() from within.

In your function example changenumber , you should definitely be using a function here. When you call timer.changenumber() , you are telling the timer to change its number. When you call timer.emit('changenumber') , you are essentially speaking on behalf of the timer that the number has already changed. Worse yet, the timer is talking to itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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