diff --git a/src/event.ts b/src/event.ts index 867dea9..793d252 100644 --- a/src/event.ts +++ b/src/event.ts @@ -1,4 +1,5 @@ import {Subscription} from './sub'; +import {EventConsumer} from './consumer'; /** * Schedule for emitting / broadcasting data to subscribers, to be used by method [[emit]]. @@ -246,6 +247,15 @@ export class SubEvent { this.options = options ?? {}; } + /** + * Returns a new [[EventConsumer]] for the event, which removes methods [[emit]] and [[cancelAll]]. + * + * This method simplifies creation of a receive-only event object. + */ + public toConsumer>(): EventConsumer { + return new EventConsumer(this); + } + /** * Subscribes to the event. * diff --git a/test/event.spec.ts b/test/event.spec.ts index 0d9c3ce..5f7edb8 100644 --- a/test/event.spec.ts +++ b/test/event.spec.ts @@ -1,5 +1,5 @@ import {chai, dummy, expect} from './'; -import {EmitSchedule, ISubContext, SubEvent} from '../src'; +import {EmitSchedule, EventConsumer, ISubContext, SubEvent} from '../src'; const errInvalidOptions = `Invalid "options" parameter.`; @@ -443,3 +443,14 @@ describe('once', () => { expect(contextOut).to.equal(contextIn); }); }); + +describe('toConsumer', () => { + it('must return new EventConsumer', () => { + const e = new SubEvent(); + const c = e.toConsumer(); + expect(c).to.be.instanceOf(EventConsumer); + expect(typeof c.subscribe).to.equal('function'); + expect((c as any).emit).to.be.undefined; + expect((c as any).cancelAll).to.be.undefined; + }); +});