M
M
Maxim Sokhryakov2018-08-05 22:17:13
Node.js
Maxim Sokhryakov, 2018-08-05 22:17:13

How does this piece of js code work?

In one of the modules received from npm I saw this at the end

return this.on('camdata', function(data) {
      return self.wsServer.broadcast(data);
    });
  };

whole method
VideoStream.prototype.pipeStreamToSocketServer = function() {
    var self;
    self = this;
    this.wsServer = new ws.Server({
      port: this.wsPort
    });
    this.wsServer.on("connection", function(socket) {
      return self.onSocketConnect(socket);
    });
    this.wsServer.broadcast = function(data, opts) {
      var i, results;
      results = [];
      for (i in this.clients) {
        if (this.clients[i].readyState === 1) {
          results.push(this.clients[i].send(data, opts));
        } else {
          results.push(console.log("Error: Client (" + i + ") not connected."));
        }
      }
      return results;
    };
    
    return this.on('camdata', function(data) {
      return self.wsServer.broadcast(data);
    });
  };


And I can't figure out what return returns?
Judging by this, this.on subscribes the current instance of an object with the VideoStream class to an event, in the handler of which an array of messages is returned (in fact, broadcast sends the received piece of data to all clients).
But what does return this.on(...); ? If nothing, what's the point?
ps this is how the code that connects this library looks like
(function() {
  var VideoStream;

  VideoStream = require('./videoStream');

  module.exports = VideoStream;

}).call(this);

And even higher is the call to the constructor of this class with the assignment of parameters.
The constructor himself
constructor
VideoStream = function(options) {
    this.name = options.name;
    this.streamUrl = options.streamUrl;
    this.width = options.width;
    this.height = options.height;
    this.wsPort = options.wsPort;
    this.inputStreamStarted = false;
    this.stream = void 0;
    this.startMpeg1Stream();
    this.pipeStreamToSocketServer();
    return this;
  };

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-08-05
@maximsohryakov

But what does return this.on(...); ? If nothing, what's the point?

And you open the code of the on method, and look. I would suggest that it returns this - to make method chaining possible.
UPD. Well, yes, it is. I found the code of the module you are talking about - VideoStream is inherited from EventEmitter, in the documentation for which it is directly stated about the on method that
Returns a reference to the EventEmitter, so that calls can be chained

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question