Skip to content

Instantly share code, notes, and snippets.

@m3g4p0p
Last active January 7, 2017 12:30
Show Gist options
  • Save m3g4p0p/339776f05de1395df16787bafa5d2f41 to your computer and use it in GitHub Desktop.
Save m3g4p0p/339776f05de1395df16787bafa5d2f41 to your computer and use it in GitHub Desktop.
A simple publish/subscribe store using a WeakMap to keep the subscribers private
const createStore = (function () {
const scope = new WeakMap
const storeProto = {
subscribe (prop, fn) {
const ownScope = scope.get(this)
ownScope.subscribers[prop] = ownScope.subscribers[prop] || []
ownScope.subscribers[prop].push(fn)
return this
},
notify (prop) {
const ownScope = scope.get(this)
if (ownScope.subscribers[prop]) {
ownScope.subscribers[prop].forEach(subscriber => {
subscriber.call(this, this[prop])
})
}
return this
},
set (prop, val) {
this[prop] = val
this.notify(prop)
return this
}
}
return function createStore (data) {
const store = Object.create(storeProto)
Object.assign(store, data)
scope.set(store, {subscribers: {}})
return store
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment