All files / src/utils/callEvent callEvent.ts

100% Statements 12/12
50% Branches 1/2
100% Functions 2/2
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 709x   9x 9x                                                                                                     9x 1x 1x 1x 1x   1x     1x 1x     1x    
import { unwatch } from '../unwatch'
 
import { forceQueueWatchers } from '../../Compute'
import { scope } from '../../constants'
 
/**
 * **Immediately executes** a reactive effect **outside of reactive tracking**.
 *
 * - **Runs callback immediately** (unlike `createEvent`)
 * - **Ignores** automatic state subscriptions (like `unwatch`)
 * - **Batches** state updates and **flushes queue** at the end
 * - Perfect for **side effects** and **mutations**
 *
 * @example Batch multiple updates
 * ```ts
 * const a = new State(0)
 * const b = new State(0)
 *
 * new Watch(() => {
 *   console.log(a.value, b.value)
 * })
 * // logs: 0, 0
 *
 * a.value = 1
 * // logs: 1, 0
 *
 * b.value = 1
 * // logs: 1, 1
 *
 * callEvent(() => {
 *   a.value = 2
 *   b.value = 2
 * })
 * // logs: 1, 1
 * ```
 *
 * @example Returns value from callback
 * ```ts
 * const count = new State(0)
 *
 * new Watch(() => console.log(count.value))
 * // logs: 0
 *
 * const prev = callEvent(() => count.value++)
 * // logs: 1
 *
 * console.log(prev)
 * // logs: 0
 * ```
 *
 * @param callback - Effect callback to execute immediately
 * @returns Result of callback execution
 * @template T - return type
 */
export function callEvent<T> (callback: () => T): T {
  const result = unwatch(() => {
    scope.eventDeep++
    const result = callback()
    scope.eventDeep--
 
    return result
  })
 
  Eif (!scope.eventDeep) {
    forceQueueWatchers()
  }
 
  return result
}