Skip to content

Instantly share code, notes, and snippets.

@Nitive
Last active January 25, 2016 17:41
Show Gist options
  • Save Nitive/f699d25c6e4cd9c5c4f0 to your computer and use it in GitHub Desktop.
Save Nitive/f699d25c6e4cd9c5c4f0 to your computer and use it in GitHub Desktop.
let store = null
const listeners = []
​
export const getStore = () => store
​
export const subscribe = fn => {
  listeners.push(fn)
+  return () => listeners.filter(l => l !== fn) // return `unsubscribe` function
}

export const changeStore = newStore => {
  store = newState
-  listeners.forEach(listener => listener())
+  listeners.forEach(listener => listener(store))
}

// usage
+ subscribe(store => {
- subscribe(() => {
-  const store = getStore()
  if (store.name !== this.state.name) {
    this.setState({ name: store.name })
  }
})
@Nitive
Copy link
Author

Nitive commented Jan 25, 2016

// подписываемся на изменения store
// переданная функция будет вызываться при каждом изменении
subscribe(store => { 
  if (store.name !== this.state.name) { // проверяем, изменились ли данные (ведь subscribe вызывается при любом изменении)
    this.setState({ name: store.name }) // если да, то меняем state
  }
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment