events.ts 1.9 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4
import { withModifiers } from 'vue'
import { normalizeNativeEvent } from '@dcloudio/uni-core'
import {
  parseEventName,
fxy060608's avatar
fxy060608 已提交
5
  decodeEvent,
fxy060608's avatar
fxy060608 已提交
6 7 8
  formatLog,
  EventModifierFlags,
  normalizeEventType,
fxy060608's avatar
fxy060608 已提交
9
  ACTION_TYPE_EVENT,
fxy060608's avatar
fxy060608 已提交
10
} from '@dcloudio/uni-shared'
fxy060608's avatar
fxy060608 已提交
11
import { VD_SYNC } from '../../../../constants'
fxy060608's avatar
fxy060608 已提交
12
import { UniCustomElement } from '../components'
fxy060608's avatar
fxy060608 已提交
13 14

export function patchEvent(el: UniCustomElement, name: string, flag: number) {
fxy060608's avatar
fxy060608 已提交
15
  const [type, options] = parseEventName(decodeEvent(name))
fxy060608's avatar
fxy060608 已提交
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
  if (flag === -1) {
    // remove
    const listener = el.__listeners[type]
    if (listener) {
      el.removeEventListener(type, listener)
    } else if (__DEV__) {
      console.error(
        formatLog(`tag`, el.tagName, el.__id, 'event[' + type + '] not found')
      )
    }
  } else {
    // add
    if (el.__listeners[type]) {
      if (__DEV__) {
        console.error(
          formatLog(
            `tag`,
            el.tagName,
            el.__id,
            'event[' + type + '] already registered'
          )
        )
      }
      return
    }
    el.__listeners[type] = createInvoker(el.__id, flag, options)
    el.addEventListener(type, el.__listeners[type], options)
  }
}

fxy060608's avatar
fxy060608 已提交
46
export function createInvoker(
fxy060608's avatar
fxy060608 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
  id: number,
  flag: number,
  options?: AddEventListenerOptions
) {
  const invoker = (evt: Event) => {
    const event = normalizeNativeEvent(evt)
    ;(event as any).type = normalizeEventType(evt.type, options)
    UniViewJSBridge.publishHandler(VD_SYNC, [[ACTION_TYPE_EVENT, id, event]])
  }
  if (!flag) {
    return invoker
  }
  return withModifiers(invoker, resolveModifier(flag))
}

function resolveModifier(flag: number) {
  const modifiers: string[] = []
  if (flag & EventModifierFlags.prevent) {
    modifiers.push('prevent')
  }
  if (flag & EventModifierFlags.self) {
    modifiers.push('self')
  }
  if (flag & EventModifierFlags.stop) {
    modifiers.push('stop')
  }
  return modifiers
}