Nodejs: How to handle event listening between objects?

后端 未结 2 1310
旧巷少年郎
旧巷少年郎 2021-02-06 08:40

I currently have the problem that I have an object which should listen on another object.

The question is: how should I handle the subscription? Currently, I only know o

2条回答
  •  暖寄归人
    2021-02-06 08:52

    Edit

    Per your comment, I'm not sure what you find unreadable about this, but you can try using Stream objects and the elegant Stream#pipe method.

    The Streams

    var Stream = require('stream').Stream;
    var util = require('util');
    
    var Sender = function() {
      this.readable = true;
      this.saySomething = function(message) {
        this.emit('data', message);
      };
    };
    util.inherits(Sender, Stream);
    
    var Receiver = function() {
      this.writable = true;
      this.write = function(message) {
        console.log('received: ' + message);
      }
    };
    util.inherits(Receiver, Stream);
    

    Usage

    // instance of each
    var s = new Sender();
    var r = new Receiver();
    
    // connect using pipe!
    s.pipe(r);
    
    // an event
    s.saySomething('hello world'); //=> received: hello world
    

    I particularly like using Stream objects. The pipe method is quite handy :) Each stream has a single input and output. I like them because it encourages you to build small, functional components that are responsible for a specific task. Then, you can chain/reuse them however you see fit.


    Original post

    You'll want to use EventEmitter

    Here's a quick example

    var events = require('events');
    var util = require('util');
    
    var SampleEmitter = function() {
        events.EventEmitter.call(this);
    
        this.sayHello = function() {
          this.emit('hello', 'hello world');
        };
    };
    util.inherits(SampleEmitter, events.EventEmitter);
    
    var SampleListener = function(emitter) {
        emitter.on('hello', function(data) {
            console.log(data);
        });
    };
    
    var se = new SampleEmitter();
    var sl = new SampleListener(se);
    
    se.sayHello(); //=> 'hello world'
    

提交回复
热议问题