简体   繁体   中英

ES6 Classes Event Emitter

Can someone point me to a decent EventEmitter (ES6) to use emit events globally across different classes? Preferably with examples? I found quite a dozen, but none with working examples between classes..

I'd love one that works as a Singleton so I don't have to extend it..

For Example (not real code):

import emitter from 'SingleTonEmitter';
export class Listener(){
const myEmitter = new Emitter()
myEmitter.on('somethingHappened', (data) => this.onChange())
}

// NEW sepatate class
import emitter from 'SingleTonEmitter';
export class DispatchClass(){
const myEmitter = new Emitter()
myEmitter.dispatch('somethingHappened','optionalData')
}

Thanks in advance!

RxJS subjects can act as general purpose event emitters. Singleton pattern is naturally handled by JS modules since they are evaluated only once and thus isn't specific to event emitter class implementation.

This is how it's done in RxJS 6:

import { Subject } from 'rxjs';
import { filter } from 'rxjs/operators';

export const filterEvent = event => filter(e => e.event === event);

export default new Subject();

import emitter, { filterEvent } from './emitter';

emitter
.pipe(filterEvent('foo'))
// or
// .pipe(filter(({ event }) => event === 'foo')))
.subscribe(e => {
  console.log(e.data)
});

emitter.next({ event: 'foo', data: {...} });

RxJS Subject is used in Angular EventEmitter implementation .

There are several subject classes that have their distinctive traits and may be preferred in some cases.

Subject class can be extended to provide syntactic sugar for pipe(filter(...)) routine if necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM