Events
Events are the things that happen to your app and handlers are the functions that are executed in response to an event. We can use events for inter-plugin communication.
Example
An example of events and handlers: Let's say we are using the Authentication plugin and we want to perform some operation as soon as the user authentication is done.
Here, we are adding an event authentication of the Auth plugin to the pluginStore. The event is dispatched when a user logs in. To name an event, you can refer to the naming conventions here
AuthPlugin.tsx
import React from "react";
import { IPlugin, PluginStore, Event } from "react-pluggable";
class AuthPlugin implements IPlugin {
activate(): void {
this.pluginStore.addEventListener("Auth.authentication", (event: any) => {
console.log(event);
});
this.pluginStore.addEventListener("Auth.authentication", (event: any) => {
console.log("Authentication successful ", event);
});
}
//rest of the code
}
export default AuthPlugin;
Note: We have to import "Event" from "react-pluggable",otherwise it will automatically get assigned Javascript's default Event class type, which doesn't work with plugins.
addEventListener is used to add a callback against a particular event and dispatchEvent is used to trigger an event.
Dispatching event from the target component:
Login.tsx
import * as React from "react";
import { usePluginStore } from "react-pluggable";
const Login = (props: any) => {
const pluginStore: any = usePluginStore();
pluginStore.dispatchEvent(new Event("Auth.authentication"));
//rest of the code
};
export default Login;