Saturday 29 July 2017

Nested eventEmitters

I have a class that manages a list of dependent items, and a class that represents the item itself. Both the item class and list class can emit events. Users don't generally need to directly manipulate the item objects as the dependency tree is the primary utility provided by the module. Is there a way to have a single event stream? I think I can do it with a singleton emitter, but I really like to stay away from singletons. Would also love to avoid re-emitting every event from the item class, (too easy to forget to add the re-emitter for a new event, also extra typing)Example of what I'd like to do. Line 45 in the example is how I'd like the consumer to interact with the events. Are singletons that ugly here? Is the re-emit pattern better than a singleton? Does it matter? ;)example: http://ift.tt/2vgwA8Z EventEmitter = require('events'); class Foo extends EventEmitter { constructor(){ super(); } fooEmit(){ this.emit('foo'); } } class Bar extends EventEmitter { constructor(foo){ super(); this.foo = foo; // Would like to not have to do this for each // event from foo this.foo.on('foo', () =>{ this.emit('re-emit foo'); }) } passthroughTest(){ this.foo.fooEmit(); } barEmit(){ this.emit('bar'); } } // Want users of Bar to get all the events from Foo bar = new Bar(new Foo()); // works (understand this, just like having a known case) bar.on('bar', ()=>{ console.log('bar emitted'); }) // passing through all of the events from Foo would be awesome bar.on('foo', () =>{ console.log('thisWorks'); }) bar.on('re-emit foo', () =>{ console.log('Would like to avoid this pattern'); }) bar.barEmit(); bar.passthroughTest();

Submitted July 29, 2017 at 01:47PM by skarfacegc

No comments:

Post a Comment