How signals and slots work for inter-object communication
masterPhosphorJS uses a type-safe publish-subscribe pattern based on Signal and Slot.
- Signal: An object (the publisher) declares one or more signals. A signal is associated with a
senderobject. - Slot: A callback function (the subscriber) that is invoked when a signal is emitted. A slot has the signature
(sender: T, args: U) => void. - Connection: A subscriber connects a slot to a signal using
signal.connect(slot, thisArg).
When a signal is emitted via signal.emit(args), all connected slots are invoked synchronously in the order they were connected. If a slot throws an exception, it is caught and passed to a global exception handler to prevent the emission loop from breaking.
import { ISignal, Signal } from '@phosphor/signaling';
class SomeClass {
constructor(name: string) {
this.name = name;
}
readonly name: string;
get valueChanged: ISignal<this, number> {
return this._valueChanged;
}
get value(): number {
return this._value;
}
set value(value: number) {
if (value === this._value) {
return;
}
this._value = value;
this._valueChanged.emit(value);
}
private _value = 0;
private _valueChanged = new Signal<this, number>(this);
}
function logger(sender: SomeClass, value: number): void {
console.log(sender.name, value);
}
let m1 = new SomeClass('foo');
m1.valueChanged.connect(logger);
m1.value = 42; // logs: foo 42