Last active
January 7, 2017 12:30
-
-
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
This file contains hidden or 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 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