Last active
July 18, 2019 04:29
-
-
Save StrongerMyself/a8cb19425f0e17f6d196c4de89932670 to your computer and use it in GitHub Desktop.
Observer Store
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
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) | |
} |
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
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