useListeners.ts 2.1 KB
Newer Older
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
import { isPlainObject } from '@vue/shared'
import { watch, onUnmounted, getCurrentInstance } from 'vue'

export function /*#__PURE__*/ useListeners(
  props: { id: string },
  listeners: Record<string, Function>
) {
  _addListeners(props.id, listeners)

  watch(
    () => props.id,
    (newId, oldId) => {
      _removeListeners(oldId, listeners, true)
      _addListeners(newId, listeners, true)
    }
  )

  onUnmounted(() => {
    _removeListeners(props.id, listeners)
  })
}

function _addListeners(
  id: string,
  listeners: Record<string, Function>,
  watch?: boolean
) {
28 29 30
  const instance = getCurrentInstance()!
  const vm = instance.proxy!
  const pageId = vm.$root!.$page.id
31 32 33 34 35 36 37 38

  if (watch && !id) {
    // id被置空
    return
  }
  if (!isPlainObject(listeners)) {
    return
  }
39

40 41 42 43
  Object.keys(listeners).forEach((name) => {
    if (watch) {
      // watch id
      if (name.indexOf('@') !== 0 && name.indexOf('uni-') !== 0) {
44
        UniViewJSBridge.on(`uni-${name}-${pageId}-${id}`, listeners[name])
45 46 47 48 49 50 51
      }
    } else {
      if (name.indexOf('uni-') === 0) {
        // 完全限定
        UniViewJSBridge.on(name, listeners[name])
      } else if (id) {
        // scoped
52
        UniViewJSBridge.on(`uni-${name}-${pageId}-${id}`, listeners[name])
53 54 55 56 57 58 59 60 61 62
      }
    }
  })
}

function _removeListeners(
  id: string,
  listeners: Record<string, Function>,
  watch?: boolean
) {
63 64 65
  const instance = getCurrentInstance()!
  const vm = instance.proxy!
  const pageId = vm.$root!.$page.id
66 67 68 69 70 71 72 73

  if (watch && !id) {
    // id之前不存在
    return
  }
  if (!isPlainObject(listeners)) {
    return
  }
74

75 76 77 78
  Object.keys(listeners).forEach((name) => {
    if (watch) {
      // watch id
      if (name.indexOf('@') !== 0 && name.indexOf('uni-') !== 0) {
79
        UniViewJSBridge.off(`uni-${name}-${pageId}-${id}`, listeners[name])
80 81 82 83 84 85 86
      }
    } else {
      if (name.indexOf('uni-') === 0) {
        // 完全限定
        UniViewJSBridge.off(name, listeners[name])
      } else if (id) {
        // scoped
87
        UniViewJSBridge.off(`uni-${name}-${pageId}-${id}`, listeners[name])
88 89 90 91
      }
    }
  })
}