ionic4-EventBus (event bus)

ionic4-EventBus (event bus)

surroundings

node 10.15.0
ionic 4.12.0
cordova 9.0
# platforms
cordova-android:8.0.0
cordova-ios: 5.0.0

Welcome to visit me:Ionic4 column

Foreword:
AngularJs, we can use b r o a d c a s t broadcast、 On to send out, listen to the broadcast, to achieve global message / event communication; in the Angular2+ version, the broadcast function is cancelled.
Below we will use the features of RxJS to implement the event bus.
Note: The code is derived fromng-event-bus

usage

first step

Import

# app.module.ts
providers: [
  NgEventBus
]

injection

# some component
constructor(private eventBus: NgEventBus){...}

Second step

Send event

this.eventBus.cast('test:start', {data: 'hahaha'});

third step

Receiving events

# 
this.eventBus.on('test:start').subscribe((message) => {
  console.log(message);
});
 # Receive all under test
this.eventBus.on('test:**').subscribe((message) => {
  console.log(message);
});

Source code analysis

Event definition

interface EventBusMessage {
  key: string;
  data?: any;
}

this._eventBus is used to send and receive events.
Why use Subject here?

What is a Subject? The RxJS Subject is a special type of Observable that allows values ​​to be multicast to multiple Observers. Although the normal Observable is unicast (each subscription's Observer has an independent implementation of Observable), the Subject is multicast.

Each Subject is an Observer. It is an object containing next(v), error(e), and complete(). To provide a new value to the Subject, simply call next(theValue), which will be multicast to the observer who has registered to accept the Subject.

constructor() {
  this._eventBus = new Subject<EventBusMessage>();
}

Send event

As with the definition of Subject, you only need to call the next method to broadcast to all observers who subscribe to this subject.

public send(key: string, data?: any): void {
  if (typeof key !== 'string' || !key.length) {
    throw Error('key must be a string and mustn\'t be empty.');
  }
  this._eventBus.next({key, data});
}

Receiving events

Parameters: event key
filter: filter key
Here is the key match, which is explained separately below.

public on<T>(key: string): Observable<T> {
  return this._eventBus.asObservable().pipe(
    filter((event: EventBusMessage): event is EventBusMessage => this.keyMatch(event.key, key)),
    map(event => <T>event.data)
  );
}

Key match
The specific analysis will be presented in the form of a comment

public keyMatch(key: string, wildcard: string): boolean {
    const w = '*';
    const ww = '**';
    
    const partMatch = (wl, k) => {
      return (wl === w) || (wl === k);
    };
    const sep = this.separator;
    // Split key etc with *: [app, start]
    const kArr = key.split(sep);
         // Listen for key splitting etc: [app,**]
    const wArr = wildcard.split(sep);
    const kLen = kArr.length;
    const wLen = wArr.length;
    const max = Math.max(kLen, wLen);
    for (let i = 0; i < max; i++) {
      const cK = kArr[i];
      const cW = wArr[i];
             // If: after matching ** && : before the undefined match
      if (cW === ww && (typeof cK !== 'undefined')) {
        return true;
      }
             // : Match before and after, 2 parts are different, match fails
      if (!partMatch(cW, cK)) {
        return false;
      }
    }
    return true;
  }

The next article will introduce the subscription management of RxJS.

Welcome to visit me:Ionic4 column

Intelligent Recommendation

Event bus: EventBus

When non-parent-child components need to communicate, in addition to vuex, there isEvent busUp Introduction EventBus is also called event bus. In Vue, you can use EventBus as a communication bridge co...

EventBus event processing bus

Write first EventBus is an event processing bus, which can replace Android's traditional Intent, Handler, Broadcast or interface functions to transfer data and execute methods between Fragment, Activi...

Android EventBus event bus

Android EventBus Preface: Mainly analyze and understand from three aspects: what is EventBus, why use EventBus and how to use EventBus. What is EventBus (what) Why use EventBus (why) How to use EventB...

EventBus 3.0 Event Bus

How to use EventBus 3.0 and some problems encountered during use Hmm~ I am a new Android programmer This is the first article I wrote on the blog, and I finally finished writing with a nervous mood De...

【Event Bus】Analyze EventBus

The above learning is based on the advanced light of Android...

More Recommendation

Flutter event bus EventBus

In Android native, there are broadcasts that can transfer data across pages. In Flutter, we can customize an event bus to transfer data across pages. step Define a singleton class Add a Map<String ...

Eventbus event bus

What is Eventbus event bus Eventbus is a message bus that implements the observer mode, used to simplify the components of the program, thread communication, can easily switch threads, open up threads...

Eventbus: Event Bus Framework

Eventbus framework First, use the scene: Second, EVENTBUS Advantages Third, EVENTBUS principle: Fourth, Eventbus use: 1. Create an event type 2. In the module that needs to be subscribed to the event,...

Android event bus Eventbus

Eventbus can be used in communication between components within the application, components and background threads Create related events OnResume registration, you can also register elsewhere Onpuse l...

Understanding of event bus (Eventbus)

Communication between VUE components is implemented as a bridge through an empty Vue instance. It is a solution to realizing non-father subcomponents 1. Create a Vue instance to export this instance 2...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top