Issue events from module Nodejs

1

Greetings, I am trying to issue an event in nodejs from a separate module, but I can not capture it, I have this code in the module

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

function MyStream (connection) {

if (!(this instanceof MyStream))
    return new MyStream(connection);
  events.EventEmitter.call(this); 

  var self = this;
  self.emit('pulse', 'client pulse');     

}

util.inherits(MyStream, events.EventEmitter);

exports.MyStream = MyStream;

and then from the main script I try to capture the event but I can not capture it

var server = require("./server");

var mystream = server.MyStream('aqui van los parametros');

mystream.on('pulse', function  (data) {
    console.log(data);
});

I'm not getting any errors either, any ideas? thanks

    
asked by danielvkp 20.06.2016 в 01:21
source

1 answer

2

You have two problems in your code

  • The names of the events do not match. On the one hand, you broadcast a event and on the other hand you try to capture the join event. Instead of:

    self.emit('pulse', ....
    ........
    mystream.on('join', ....
    

    It should be

    self.emit('pulse', ....
    ........
    mystream.on('pulse', ....
    

    The names of the events that are broadcast and captured must match.

  • You are trying to issue the event within the same constructor of the object. This will cause that when you finish the setup of your event handler the event has already been broadcast and your code will not capture it anyway.

    var mystream = server.MyStream('aqui van los parametros');
    // Cuando llegas a esta línea de código ya el evento se ha emitido
    mystream.on('join', ..........
    

    To prove this point, just set a timeout inside the constructor of your object and you will see the event emit without problems. This is a replacement for your server.js

    file
    function MyStream (connection) {
        // Es una buena práctica ponerle llaves a todos tus bloques aunque sean de una sola línea
        // Lee http://jshint.com/docs/options/#curly
        if (!(this instanceof MyStream)) {
            return new MyStream(connection);
        }
        events.EventEmitter.call(this);
    
        var self = this;
    
        // Este código es sólamente para una demostración
        setTimeout(function () {
            self.emit('pulse', 'client pulse');
        }, 3000);
    }
    

    And for the other file

     var server = require("./server");
    
     var mystream = server.MyStream('aqui van los parametros');
    
     mystream.on('pulse', function  (data) {
         console.log(data);
     });
    

    And the result is shown in the photo

  • answered by 20.06.2016 / 14:55
    source