Skip to content

Instantly share code, notes, and snippets.

@StrongerMyself
Last active July 18, 2019 04:29
Show Gist options
  • Save StrongerMyself/a8cb19425f0e17f6d196c4de89932670 to your computer and use it in GitHub Desktop.
Save StrongerMyself/a8cb19425f0e17f6d196c4de89932670 to your computer and use it in GitHub Desktop.
Observer Store
export const deepCopy = (data) => {
return typeof data === 'object' ? (
JSON.parse(JSON.stringify(data))
) : (
data
)
}
export function Store(_init) {
let init = deepCopy(_init)
let state = deepCopy(_init)
let observers = []
const broadcast = () => {
observers.forEach(subscriber => subscriber(state))
}
const setState = (data) => {
state = deepCopy(data)
broadcast()
}
Object.defineProperty(this, 'state', {
get: () => state,
set: setState
})
this.subscribe = (fn) => {
observers.push(fn)
fn(state)
return () => this.unsubscribe(fn)
}
this.unsubscribe = (fn) => {
observers = observers.filter(subscriber => subscriber !== fn)
}
this.reset = () => setState(init)
}
const Store = require('./store')
const counter = new Store(0)
let s1 = counter.subscribe(data => console.log('subscribe 1: ', data))
// subscribe 1: 0
let s2 = counter.subscribe(data => console.log('subscribe 2: ', data))
// subscribe 2: 0
console.log(counter.state)
// 0
counter.state = 1
// subscribe 1: 1
// subscribe 2: 1
console.log(counter.state)
// 1
counter.reset()
// subscribe 1: 0
// subscribe 2: 0
console.log(counter.state)
// 0
setTimeout(() => {
s1()
counter.state = 2
// subscribe 2: 2
console.log(counter.state)
// 2
}, 3000)
s2()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment