Skip to content

Instantly share code, notes, and snippets.

@isaaclyman
Last active July 26, 2020 03:02
Show Gist options
  • Save isaaclyman/2b7a2e98e1899d99192f9d249aad97f9 to your computer and use it in GitHub Desktop.
Save isaaclyman/2b7a2e98e1899d99192f9d249aad97f9 to your computer and use it in GitHub Desktop.
Simple class for subscribable objects with state and multiple subscribers
export class Subscribable {
constructor(name) {
this._name = name
this._subscribers = []
this._state = undefined
}
getState() {
return this._state
}
onEvent(fn) {
this._subscribers.push(fn)
}
removeSubscriber(fn) {
const ix = this._subscribers.indexOf(fn)
if (ix === -1) {
console.warn(
`Attempted to remove subscriber '${fn}' from Subscribable '${this._name}', but subscriber was not found.`
)
return
}
this._subscribers.splice(ix, 1)
}
trigger(value) {
this._state = value
for (const s of this._subscribers) {
s(value)
}
}
}
export type Subscriber<T> = (value: T) => void
export class Subscribable<T> {
private _name: string;
private _subscribers: Subscriber<T>[] = [];
private _state: T | undefined = undefined;
constructor(name: string) {
this._name = name
}
getState() {
return this._state
}
onEvent(fn: Subscriber<T>) {
this._subscribers.push(fn)
}
removeSubscriber(fn: Subscriber<T>) {
const ix = this._subscribers.indexOf(fn)
if (ix === -1) {
console.warn(
`Attempted to remove subscriber '${fn}' from Subscribable '${this._name}', but subscriber was not found.`
)
return
}
this._subscribers.splice(ix, 1)
}
trigger(value: T) {
this._state = value
for (const s of this._subscribers) {
s(value)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment