jwidget/Listenable

Consumption

import Listenable from "jwidget/Listenable";

Default export#

Hierarchy#

Description#

M
Message.

Container for callback functions. Provides basic message listening functionality. Has a sub-interface IDispatcher that can dispatch messages.

It is smart to store a dispatcher as IDispatcher internally, and expose it as Listenable externally to deny direct control over the dispatcher by its listeners.

class Example {
    private _onChange = new Dispatcher<number>();

    get onChange(): Listenable<number> {
        return this._onChange;
    }

    // ...

        // We can't dispatch public onChange, but we can dispatch private _onChange
        this._onChange.dispatch(value);

    // ...
}

Fields#

dummy#

readonly dummy: boolean

Checks if this dispatcher is dummy. This knowledge may help you do certain code optimizations.

Methods#

listen#

(handler: (message: M) => void, scope?: any): Destroyable

handler
Message handler function.
scope
handler call scope.
returns
Listener reference.

Starts listening messages.

Whenever a message is dispatched, handler function is called. Handlers are called in the same order as they were bound.

You can stop listening messages by destroying the returned listener reference. Consider using own method for this purpose.

class MyListener extends Class {
    constructor(onChange: Listenable<number>) {
        super();
        this.own(onChange.listen(message => {
            console.log("Value has changed to " + message);
        }));
    }
}