From 673a7f44a9e000e716a83312d0b46e74ccb879f3 Mon Sep 17 00:00:00 2001 From: Greg Fodor <gfodor@gmail.com> Date: Wed, 21 Mar 2018 10:27:45 -0700 Subject: [PATCH] Feedback from PR --- src/react-components/profile-entry-panel.js | 4 ++-- src/storage/store.js | 24 ++++++--------------- 2 files changed, 9 insertions(+), 19 deletions(-) diff --git a/src/react-components/profile-entry-panel.js b/src/react-components/profile-entry-panel.js index d1dca9acf..28c8cd7d9 100644 --- a/src/react-components/profile-entry-panel.js +++ b/src/react-components/profile-entry-panel.js @@ -14,7 +14,7 @@ class ProfileEntryPanel extends Component { super(props); window.store = this.props.store; this.state = {name: this.props.store.state.profile.display_name}; - this.props.store.subscribe(this.storeUpdated); + this.props.store.addEventListener("statechanged", this.storeUpdated); } storeUpdated = () => { @@ -35,7 +35,7 @@ class ProfileEntryPanel extends Component { } componentWillUnmount() { - this.props.store.unsubscribe(this.storeUpdated); + this.props.store.removeEventListener('statechanged', this.storeUpdated); } render () { diff --git a/src/storage/store.js b/src/storage/store.js index 0963baddd..5b00b7ac8 100644 --- a/src/storage/store.js +++ b/src/storage/store.js @@ -4,6 +4,7 @@ import { Validator } from "jsonschema"; const LOCAL_STORE_KEY = "___mozilla_duck"; const STORE_STATE_CACHE_KEY = Symbol(); const validator = new Validator(); +import { EventTarget } from "event-target-shim" // Durable (via local-storage) schema-enforced state that is meant to be consumed via forward data flow. // (Think flux but with way less incidental complexity, at least for now :)) @@ -30,10 +31,10 @@ export const SCHEMA = { additionalProperties: false } -export default class Store { - subscribers = new Set(); - +export default class Store extends EventTarget { constructor() { + super(); + if (localStorage.getItem(LOCAL_STORE_KEY) === null) { localStorage.setItem(LOCAL_STORE_KEY, JSON.stringify({ id: uuid() })); } @@ -47,34 +48,23 @@ export default class Store { return this[STORE_STATE_CACHE_KEY]; } - subscribe(subscriber) { - this.subscribers.add(subscriber); - } - - unsubscribe(subscriber) { - this.subscribers.delete(subscriber); - } - update(newState) { if (newState.id) { - console.error("Store id is immutable."); - return; + throw "Store id is immutable."; } const finalState = { ...this.state, ...newState }; const isValid = validator.validate(finalState, SCHEMA).valid; if (!isValid) { - console.warn(`Write of ${JSON.stringify(finalState)} to store failed schema validation.`) + throw `Write of ${JSON.stringify(finalState)} to store failed schema validation.`; return; } localStorage.setItem(LOCAL_STORE_KEY, JSON.stringify(finalState)); delete this[STORE_STATE_CACHE_KEY]; - for (const subscriber of this.subscribers) { - subscriber(); - } + this.dispatchEvent(new CustomEvent("statechanged")); return finalState; } -- GitLab