Skip to content

Instantly share code, notes, and snippets.

@ovcharik
Last active November 27, 2018 15:39
Show Gist options
  • Save ovcharik/ac4cc256853708d66126e90948b62eb8 to your computer and use it in GitHub Desktop.
Save ovcharik/ac4cc256853708d66126e90948b62eb8 to your computer and use it in GitHub Desktop.
class Observable {
protected listeners: Map< any, Function > = new Map();
constructor() {}
public subscribe(listener: any, next: Function) {
this.listeners.set(listener, next);
}
public unsibscribe(listener: any) {
this.listeners.delete(listener);
}
public next(...args: any[]) { /* TODO */ }
};
class SyncStateSubjet extends Observable {
private isUpdating: boolean = false;
private state: any;
constructor() {
super();
}
public next(listener: any, state: any) {
if (this.isUpdating) { return; }
this.isUpdating = true;
this.state = state;
Array.from(this.listeners.entries()).forEach(([ l, cb ]) => {
if (l === listener) { return; }
cb(this.state);
});
this.nextTick(() => {
this.isUpdating = false;
})
}
private nextTick(cb: Function) {
setTimeout(cb, 0);
}
}
// ------------
const any: any = (...args: any[]) => {}
const input: any = (...args: any[]) => {};
class RouterListener {
constructor(
private syncState: SyncStateSubjet,
private router: any
) {
this.syncState.subscribe(this, (state) => {
this.router.next(state);
});
this.router.on('stateChanged', (state) => {
this.syncState.next(this, state);
})
}
state() {
return this.router.state();
}
$onDestroy() {
this.syncState.unsibscribe(this);
}
}
class FormListener {
@input('filter-1') filter1: Observable;
@input('filter-2') filter2: Observable;
@input('filter-3') filter3: Observable;
constructor(
private syncState: SyncStateSubjet
) {
any([
this.filter1,
this.filter2,
this.filter3
]).subscribe((state) => {
this.syncState.next(this, state);
});
this.syncState.subscribe(this, (state) => {
this.filter1.next(state[0]);
this.filter2.next(state[1]);
this.filter3.next(state[2]);
});
}
$onDestroy() {
this.syncState.unsibscribe(this);
}
}
class ListLoader {
constructor(
private syncState: SyncStateSubjet,
private routerListener: RouterListener,
) {
const state = this.routerListener.state();
this.load(...state);
this.syncState.next(this.routerListener, state);
this.syncState.subscribe(this, ([ filter1, filter2, filter3 ]) => {
this.load(filter1, filter2, filter3);
});
}
load(...args: any[]) { /* TODO */ }
$onDestroy() {
this.syncState.unsibscribe(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment