Switch to use `Set`

Since sets have a built in `.delete` method, we can avoid the gnarly `.splice` stuff in the unsubscribe function.
pull/4216/head
trbrc 6 years ago committed by GitHub
parent 84573a908c
commit eaa34164bf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -184,33 +184,31 @@ You can create your own stores without relying on [`svelte/store`](docs#svelte_s
/* Example: a custom writable store for `location.hash` */ /* Example: a custom writable store for `location.hash` */
const subscriptions = [];
let storeValue = location.hash; // Set initial value let storeValue = location.hash; // Set initial value
const subscriptions = new Set();
const hashStore = { const hashStore = {
subscribe(subscription) { subscribe(subscription) {
subscription(storeValue); // Call subscription with current value subscription(storeValue); // Call subscription with current value
subscriptions.push(subscription); // Subscribe to future values const item = {subscription};
subscriptions.add(item); // Subscribe to future values
return () => { // Return an "unsubscribe" function return () => { // Return an "unsubscribe" function
const index = subscriptions.indexOf(subscription); subscriptions.delete(item); // Remove the subscription
if (index !== -1) {
subscriptions.splice(index, 1); // Remove the subscription
}
}; };
}, },
set(hash) { set(hash) {
storeValue = hash; // Set the value
location.hash = hash; // Update location.hash location.hash = hash; // Update location.hash
for (const subscription of subscriptions) { storeValue = location.hash; // Set the value
for (const {subscription} of subscriptions) {
// Call all subscriptions // Call all subscriptions
subscription(storeValue); subscription(storeValue);
} }
} }
}; };
// Event listener to stay in sync with external changes
window.addEventListener('hashchange', () => { window.addEventListener('hashchange', () => {
// Keep the store in sync with external changes
if (location.hash !== storeValue) { if (location.hash !== storeValue) {
hashStore.set(location.hash); hashStore.set(location.hash);
} }

Loading…
Cancel
Save