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 and global subscriptions
Section titled “Owned and global subscriptions”| 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.
Static methods
Section titled “Static methods”subscribe()
Section titled “subscribe()”EventBus.subscribe(owner: object, event: string, callback: (data: any) => void): voidEventBus.subscribe(event: string, callback: (data: any) => void): voidRegisters 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 tosend().
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)); }}send()
Section titled “send()”EventBus.send(event: string, data?: any): voidCalls every subscriber of event with data. Subscriptions whose owner has been destroyed are skipped and removed.
EventBus.send("user:login", { name: "Alice" });unsubscribe()
Section titled “unsubscribe()”EventBus.unsubscribe(event: string, callback: Function): voidRemoves 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);unsubscribeAll()
Section titled “unsubscribeAll()”EventBus.unsubscribeAll(owner: object): voidRemoves every subscription owned by owner, across all events. Global subscriptions are not touched. View.destroy() calls it for you.
clear()
Section titled “clear()”EventBus.clear(): voidRemoves every listener of every event. Called by unmount().