Interface Mediator<Context, EventName>

Mediator

Description

Represents a Mediator instance with specific context and event names.

interface Mediator<Context, EventName> {
    getContext(): Readonly<Context>;
    off(event, listener): void;
    on(event, listener): void;
    send(event, modifier?): void;
}

Type Parameters

  • Context extends MediatorContext

    The type of the MediatorContext.

  • EventName extends string

    The type of the event names.

Methods

  • Gets the current context in a readonly format.

    Returns Readonly<Context>

    The readonly current context.

    Method

    Example

    // Get and log the current context.
    const currentContext = myMediator.getContext()
    console.log('Current context:', currentContext)
  • Removes an event listener from the Mediator.

    Parameters

    Returns void

    Method

    Example

    // Use .off  to listen the event once
    const myListener = (ctx: Readonly<MyContext>) => {
    console.log('my listener')
    myMediator.off('item:purchase', myListener)
    }
    myMediator.on('item:purchase', myListener)
  • Adds an event listener to the Mediator.

    Parameters

    Returns void

    Method

    Example

    // to listen to a specific event
    myMediator.on('item:add', (ctx: Readonly<MyContext>) =>
    console.log(`product added`)
    )

    // to listen to any event
    myMediator.on('*', (ctx: Readonly<MyContext>, event: MyEvent) =>
    console.log(`${event} modify context to`, ctx))
    )
  • Sends an event through the Mediator, optionally modifying the context.

    Parameters

    Returns void

    Method

    Example

    // Send a specific event with context modification.
    myMediator.send('item:add', (ctx: Readonly<MyContext>) => ({
    ...ctx,
    items: [...ctx.items, 123]
    }))

    // Send a specific event without context modification.
    myMediator.send('item:purchase')