* Returns a function that can be used on a `value` declaration to a Polymer * property. It updates the `polymerProperty` when storage changes -- i.e., * when `useLocalStorage`, it listens to storage change from another tab and * when `useLocalStorage=false`, it listens to hashchange.
(key: string, options: StorageOptions<T>)
| 151 | * when `useLocalStorage=false`, it listens to hashchange. |
| 152 | */ |
| 153 | function getInitializer(key: string, options: StorageOptions<T>): Function { |
| 154 | const fullOptions = { |
| 155 | defaultValue: options.defaultValue, |
| 156 | polymerProperty: key, |
| 157 | useLocalStorage: false, |
| 158 | ...options, |
| 159 | }; |
| 160 | return function () { |
| 161 | const uriStorageName = getURIStorageName(this, key); |
| 162 | // setComponentValue will be called every time the underlying storage |
| 163 | // changes and is responsible for ensuring that new state will propagate |
| 164 | // to the component with specified property. It is important that this |
| 165 | // function does not re-assign needlessly, to avoid Polymer observer |
| 166 | // churn. |
| 167 | const setComponentValue = () => { |
| 168 | const storedValue = get(uriStorageName, fullOptions); |
| 169 | const currentValue = this[fullOptions.polymerProperty]; |
| 170 | if (!_.isEqual(storedValue, currentValue)) { |
| 171 | this[fullOptions.polymerProperty] = storedValue; |
| 172 | } |
| 173 | }; |
| 174 | const addListener = fullOptions.useLocalStorage |
| 175 | ? addStorageListener |
| 176 | : addHashListener; |
| 177 | // TODO(stephanwlee): When using fakeHash, it _should not_ listen to the |
| 178 | // window.hashchange. |
| 179 | const listenKey = addListener(() => setComponentValue()); |
| 180 | if (fullOptions.useLocalStorage) { |
| 181 | storageListeners.push(listenKey); |
| 182 | } else { |
| 183 | hashListeners.push(listenKey); |
| 184 | } |
| 185 | // Set the value on the property. |
| 186 | setComponentValue(); |
| 187 | return this[fullOptions.polymerProperty]; |
| 188 | }; |
| 189 | } |
| 190 | function disposeBinding() { |
| 191 | hashListeners.forEach((key) => removeHashListenerByKey(key)); |
| 192 | storageListeners.forEach((key) => removeStorageListenerByKey(key)); |
nothing calls this directly
no test coverage detected
searching dependent graphs…