Skip to content

⬅️ Back to Table of Contents

📄 createDisposableDirective

📊 Analysis Summary

Metric Count
🔧 Functions 2
📦 Imports 6
📑 Type Aliases 1

📚 Table of Contents

🛠️ File Location:

📂 packages/shared/createDisposableDirective/index.ts

📦 Imports

Name Source
DirectiveBinding vue
EffectScope vue
FunctionDirective vue
ObjectDirective vue
VNode vue
effectScope vue

Functions

createDisposableDirective(origin: originDirective<H, V, A>): originDirective<H, V, A>

Utility for authoring disposable directives. Reactive effects created within mounted directive hook will be tracked and automatically disposed when directive is unmounted.

See: https://vueuse.org/createDisposableDirective

Tags: @__NO_SIDE_EFFECTS__

Raw JSDoc
/**
 * Utility for authoring disposable directives. Reactive effects created within `mounted` directive hook will be tracked and automatically disposed when directive is unmounted.
 *
 * @see https://vueuse.org/createDisposableDirective
 *
 * @__NO_SIDE_EFFECTS__
 */

Calls:

  • isFunc
  • scopeWeakMap.get
  • effectScope (from vue)
  • scopeWeakMap.set
  • scope.run
  • mounted
  • scopeWeakMap.get(el)?.stop
  • scopeWeakMap.delete
  • unmounted
Code
export function createDisposableDirective<H extends HTMLElement, V, A = any>(origin: originDirective<H, V, A> = {}): originDirective<H, V, A> {
  function isFunc(fn: unknown) {
    return typeof fn === 'function'
  }

  const normalisedOrigin = isFunc(origin) ? { mounted: origin, updated: origin } : origin

  const { mounted, unmounted } = normalisedOrigin

  if (!isFunc(mounted))
    return origin

  const scopeWeakMap = new WeakMap<H, EffectScope>()

  return {
    ...normalisedOrigin,
    mounted(el: H, binding: DirectiveBinding<V, string, A>, vNode: VNode<any, H>, prevNode: null) {
      const scope = scopeWeakMap.get(el) ?? effectScope()
      scopeWeakMap.set(el, scope)
      scope.run(() => {
        mounted?.(el, binding, vNode, prevNode)
      })
    },
    unmounted(el: H, binding: DirectiveBinding<V, string, A>, vNode: VNode<any, H>, prevNode: null) {
      scopeWeakMap.get(el)?.stop()
      scopeWeakMap.delete(el)
      if (isFunc(unmounted)) {
        unmounted(el, binding, vNode, prevNode)
      }
    },
  }
}

Internal helpers

Declared inside another function in this file.

isFunc(fn: unknown): boolean

Parameters:

  • fn unknown

Returns: boolean

Code
function isFunc(fn: unknown) {
    return typeof fn === 'function'
  }

Type Aliases

originDirective<H, V, A>

type originDirective<H, V, A> = FunctionDirective<H, V, string, A> | ObjectDirective<H, V, string, A>;

Generated by Syntax Scribe