-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
47 lines (42 loc) · 967 Bytes
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { toWritable } from "../utils"
import type { MaybeStore, Watchable } from "../utils"
/**
* Creates a watchable store that calls a function when the value changes.
*
* @param initialValue - Initial value to start watching
*
* @param fn - Function to call when the value changes
*
* @see https://vuejs.org/guide/essentials/watchers.html
*
* @example
* ```ts
* const count = watchable(0, (o, n) => {
* console.log(`count changed from ${o} to ${n}`)
* })
* ```
*
* @returns A writable store that calls a function when the value changes
*/
export function watchable<T>(
initialValue: MaybeStore<T>,
fn: (o: T, n: T) => void
): Watchable<T> {
const { subscribe, update } = toWritable(initialValue)
let active = true
return {
subscribe,
set: (value: T) => {
update((old_value) => {
if (active) fn(old_value, value)
return value
})
},
pause: () => {
active = false
},
resume: () => {
active = true
},
}
}