Skip to main content

Subscribe to an Existing Event

Events can only be created, published, and subscribed to from within a custom service, component model, or component. This article will walk you through subscribing to the ui.activated event from within a custom service.

Prerequisites

Create the Custom Service

Create a custom service with an _onInitialized and _onDestroy method.

src/services/CustomService.ts
import { ServiceBase } from "@vertigis/web/services";

export default class CustomService extends ServiceBase {
handles: IHandle[] = [];

protected async _onInitialize(): Promise<void> {
await super._onInitialize();
}

public async _onDestroy(): Promise<void> {
await super._onDestroy();
}
}

Register the Custom Service

Register the custom service in src/index.ts and set it to load on startup.

src/index.ts
import { LibraryRegistry } from "@vertigis/web/config";
import CustomService from "./services/CustomService";

export default function (registry: LibraryRegistry) {
registry.registerService({
id: "custom-service",
getService: (config) => new CustomService(config),
loadOnStartup: true,
});
}

Subscribe to the Event

Subscribe to the ui.activated event.

src/services/CustomService.ts
import { ServiceBase } from "@vertigis/web/services";

export default class CustomService extends ServiceBase {
handles: IHandle[] = [];

protected async _onInitialize(): Promise<void> {
await super._onInitialize();
this.handles.push(
this.messages.events.ui.activated.subscribe(
(id: string) => {
console.log(`Component '${id}' activated.`);
}
)
);
}

protected async _onDestroy(): Promise<void> {
await super._onDestroy();
this.handles.forEach((handle) => handle.remove());
}
}