All files / src/utils/createEvent createEvent.ts

100% Statements 13/13
100% Branches 1/1
100% Functions 3/3
100% Lines 13/13

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 347x 7x 7x                             7x 5x 5x 5x 5x 5x 5x     5x 5x     5x      
import { scope } from '../../constants'
import { forceQueueWatchers } from '../../helpers'
import { unwatch } from '../unwatch'
 
/**
 * You can create event function with createEvent
 * ```typescript
 * import { State, createEvent } from 'watch-state'
 *
 * const count = new State(0)
 * const increase = createEvent(() => {
 *   console.log(count.value++)
 * })
 *
 * new Watch(increase)
 * ```
 * */
export function createEvent<F extends Function> (fn: F): F {
  return function () {
    const result = unwatch(() => {
      scope.eventDeep++
      const result = fn.apply(this, arguments)
      scope.eventDeep--
      return result
    })
 
    if (!scope.eventDeep) {
      forceQueueWatchers()
    }
 
    return result
  } as unknown as F
}