Last active
October 16, 2019 06:26
-
-
Save CEOmurky/f10ac4ac90026d93d5cf55c36637f154 to your computer and use it in GitHub Desktop.
easy subscribe Stroe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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