Created
June 4, 2022 00:50
-
-
Save frangio/20e29b429a3a335ec560286675ac34bc to your computer and use it in GitHub Desktop.
A helper to build custom Svelte stores
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
import type { Subscriber } from 'svelte/store'; | |
export function store<T>(start: () => T, stop?: () => void) { | |
const subscribers = new Set<Subscriber<T>>(); | |
let value: T; | |
function notify() { | |
for (const fn of subscribers) { | |
fn(value); | |
} | |
} | |
function set(newValue: T) { | |
const oldValue = value; | |
value = newValue; | |
if (!Object.is(newValue, oldValue)) { | |
notify(); | |
} | |
} | |
function subscribe(fn: Subscriber<T>) { | |
if (subscribers.size === 0) { | |
value = start(); | |
} | |
fn(value); | |
subscribers.add(fn); | |
return () => { | |
subscribers.delete(fn); | |
if (subscribers.size === 0) { | |
stop?.(); | |
} | |
}; | |
} | |
return { | |
subscribe, | |
notify, | |
set, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment