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
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.
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);
// 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.
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'