Skip to content

EventBus

EventBus is a static publish/subscribe channel for communication between views. All methods are static; there is no instance.

import { EventBus } from "jops-core";

Learn more: Events.

Owned Global
Call subscribe(owner, event, callback) subscribe(event, callback)
Removed automatically when the owner (a view) is destroyed only when you call unsubscribe()
Use inside views app-level code outside views

Prefer the owned form inside views. A global subscription made by a view keeps that view in memory and keeps calling it after it is destroyed, until you unsubscribe it.

EventBus.subscribe(owner: object, event: string, callback: (data: any) => void): void
EventBus.subscribe(event: string, callback: (data: any) => void): void

Registers a listener for event.

Parameters

  • owner (owned form): the object that owns the subscription, usually a view (this). The subscription is removed when the owner is destroyed (removeSubView(), the Router, unmount()).
  • event: the event name, for example "user:login".
  • callback: called with the payload passed to send().
import { View, EventBus } from "jops-core";
class Header extends View {
onLayout() {
// owned: removed when this view is destroyed
EventBus.subscribe(this, "user:login", (user) => this.showUser(user));
}
}
EventBus.send(event: string, data?: any): void

Calls every subscriber of event with data. Subscriptions whose owner has been destroyed are skipped and removed.

EventBus.send("user:login", { name: "Alice" });
EventBus.unsubscribe(event: string, callback: Function): void

Removes one listener (owned or global) by reference. Pass the exact function given to subscribe(); an inline arrow function can’t be unsubscribed later, so keep a reference.

const onLogin = (user) => console.log(user.name);
EventBus.subscribe("user:login", onLogin);
EventBus.unsubscribe("user:login", onLogin);
EventBus.unsubscribeAll(owner: object): void

Removes every subscription owned by owner, across all events. Global subscriptions are not touched. View.destroy() calls it for you.

EventBus.clear(): void

Removes every listener of every event. Called by unmount().