0.0.4 • Published 5 years ago

rx-event-bus v0.0.4

Weekly downloads
17
License
-
Repository
-
Last release
5 years ago

基于rxjs的轻量级event bus。使用场景:跨组件传递消息。

npm install rx-event-bus

  • 定义事件
export enum DemoEvent {
  demoChange = 'DEMO:CHANGE'
}
  • 发布消息
this.eventBus.publish(DemoEvent.demoChange, {name: 'alvin'});
  • 订阅消息
    this.demo$ = this.eventBus.subscribe(DemoEvent.demoChange)
      .pipe(takeWhile(() => this.alive));
  • angular中使用完整Demo:
import {Component, OnDestroy, OnInit} from '@angular/core';
import {RxEventBusService} from './rx-event-bus.service';
import {takeWhile} from 'rxjs/operators';

export enum DemoEvent {
  demoChange = 'DEMO:CHANGE'
}

@Component({
  selector: 'lib-rx-event-bus-demo',
  template: `
    <div>{{(demo$ | async)?.name}}</div>
  `,
})
export class RxEventBusDemoComponent implements OnInit, OnDestroy {

  private alive = true;

  demo$;

  constructor(private eventBus: RxEventBusService) {
  }

  ngOnInit() {
    // 发布消息
    this.eventBus.publish(DemoEvent.demoChange, {name: 'alvin'});

    // 订阅消息
    this.demo$ = this.eventBus.subscribe(DemoEvent.demoChange)
      .pipe(takeWhile(() => this.alive));
  }

  ngOnDestroy(): void {
    this.alive = false;
  }

}
  • 适配ng依赖注入体系,如果非ng,手动实例化RxEventBusService即可。
0.0.4

5 years ago

0.0.3

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago