简体   繁体   English

ES6类事件发射器

[英]ES6 Classes Event Emitter

Can someone point me to a decent EventEmitter (ES6) to use emit events globally across different classes? 有人可以指出我一个体面的EventEmitter(ES6),以在不同类之间全局使用发射事件吗? 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.. 我会喜欢一个可以用作Singleton的人,所以不必扩展它。

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. RxJS主题可以充当通用事件发射器。 Singleton pattern is naturally handled by JS modules since they are evaluated only once and thus isn't specific to event emitter class implementation. JS模块自然会处理Singleton模式,因为它们仅被评估一次,因此并不特定于事件发射器类的实现。

This is how it's done in RxJS 6: 这是在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 . RxJS Subject用于Angular EventEmitter实现

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. 如有必要,可以扩展Subject类以为pipe(filter(...))例程提供语法糖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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