Kopie van https://gitlab.com/studieverenigingvia/ict/centurion met een paar aanpassingen
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
41 lines
1007 B
41 lines
1007 B
4 years ago
|
import {useEffect, useState} from "react";
|
||
|
|
||
|
export class Sub<T> {
|
||
|
_listeners: ((obj: T) => void)[] = [];
|
||
|
_current: any = null;
|
||
|
|
||
|
subscribe(listener: any) {
|
||
|
if (this._listeners.indexOf(listener) < 0) {
|
||
|
this._listeners.push(listener);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
unsubscribe(listener: any) {
|
||
|
let index = this._listeners.indexOf(listener);
|
||
|
if (index >= 0) {
|
||
|
this._listeners.splice(index, 1);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
get() {
|
||
|
return this._current;
|
||
|
}
|
||
|
|
||
|
set(obj: T) {
|
||
|
this._current = obj;
|
||
|
this._listeners.forEach(cb => cb(obj));
|
||
|
}
|
||
|
}
|
||
|
|
||
|
export function useSub<T>(sub: Sub<T>, effectChanges: ((v: T) => any[]) | null = null): T {
|
||
|
const [currentState, stateSetter] = useState(sub.get());
|
||
|
|
||
|
useEffect(() => {
|
||
|
let listener = (obj: T) => stateSetter(obj);
|
||
|
sub.subscribe(listener);
|
||
|
return () => sub.unsubscribe(listener);
|
||
|
}, effectChanges ? effectChanges(currentState) : []);
|
||
|
|
||
|
return currentState;
|
||
|
}
|