SharePoint Framework publish-subscribe event messaging

Loosely coupled SPFx web parts through raising events to subscribers


Communication between the SPFx client side web parts through publish-subscribe events messaging has one big advantage, to make the components loosely coupled. That means few smaller SharePoint Framework web parts than one big monolith webpart. Because the functionality is split across smaller web parts the code base is smaller per web part so better extensibility and maintainability. Few SPFx web parts that can work as standalone, but also as composition on a SharePoint site page. See also Wikipedia on the publish-subscribe pattern.


Emit an event towards SPFx ReactiveX (RxJs) Event Emitter


I published another sample that shows how we can use the ReactiveX (RxJs) library with the SharePoint Framework to communicate between web parts through broadcasting events. Works in a similar fashion with the Event Aggregator, but the api is our custom implementation. Here is the sample link: SPFx ReactiveX (RxJs) Event Emitter Sample Emit event (broadcast message):



import { RxJsEventEmitter } from '../../../libraries/rxJsEventEmitter/RxJsEventEmitter';
import { EventData } from '../../../libraries/rxJsEventEmitter/EventData';
/**
* Publisher (Observable) React component that broadcasts messages to Subscribers (Observers).
*/
export default class Broadcaster extends React.Component<IBroadcasterProps, IBroadcasterState> {

private readonly _eventEmitter: RxJsEventEmitter = RxJsEventEmitter.getInstance();
...
/**
* Broadcasts data to all the subscribers.
*/
protected broadcastData(): void {
....
this._eventEmitter.emit("myCustomEvent:start", { id: 1, name: "Velin Georgiev" } as EventData);
}


Subscribe to an event


import { RxJsEventEmitter } from "../../../libraries/rxJsEventEmitter/RxJsEventEmitter";
import { EventData } from "../../../libraries/rxJsEventEmitter/EventData";

/**
* Subscriber (Observer) React component that Receives broadcasted messages from Publisher (Observable).
*/
export default class Receiver extends React.Component<IReceiverProps, IReceiverState> {

private readonly _eventEmitter: RxJsEventEmitter = RxJsEventEmitter.getInstance();

constructor(props: IReceiverProps) {
...
// subscribe for event by event name.
this._eventEmitter.on("myCustomEvent:start", this.receivedEvent.bind(this));
}

/**
* Method that handles Received event from the RxJsEventEmitter.
* @param data the event object of the raised event.
*/
protected receivedEvent(data: EventData): void {
...
}


Thanks to Miguel Rabaca from Spanish Point and Austin Breslin. Miguel created the sample with the SPFx event aggregator while I was working on the ReactiveX one, but myself and Austin refactored it to be testable.


Here is the SPFx RxJs Github sample