Skip to content

Instantly share code, notes, and snippets.

@CEOmurky
Last active October 16, 2019 06:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CEOmurky/f10ac4ac90026d93d5cf55c36637f154 to your computer and use it in GitHub Desktop.
Save CEOmurky/f10ac4ac90026d93d5cf55c36637f154 to your computer and use it in GitHub Desktop.
easy subscribe Stroe
class Store<T> {
private initialValue: T;
private subscribers: ((nextValue: T)=> void)[] = [];
constructor(initialValue?: T) {
this.initialValue = initialValue;
}
set(nextValue: T) {
this.initialValue = nextValue;
this.subscribers.forEach((sub) => sub(nextValue));
}
get(): T {
return this.initialValue;
}
/** value가 변경된 경우 callback의 해당 값을 보내줌 */
watch(callback: (nextValue: T) => void){
this.subscribers.push(callback);
const index = this.subscribers.length -1;
return {unWatch : this.unWatch.bind(this, index)};
}
private unWatch(index: number) {
this.subscribers.splice(index, 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment