index.js 1.1 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5
import {
  cached,
  camelize
} from 'uni-shared'

fxy060608's avatar
fxy060608 已提交
6 7
const MPPage = Page
const MPComponent = Component
fxy060608's avatar
fxy060608 已提交
8 9 10 11 12 13 14 15

const customizeRE = /:/g

const customize = cached((str) => {
  return camelize(str.replace(customizeRE, '-'))
})

function initTriggerEvent (mpInstance) {
fxy060608's avatar
fxy060608 已提交
16 17 18 19 20
  if (__PLATFORM__ === 'mp-weixin' || __PLATFORM__ === 'app-plus') {
    if (!wx.canIUse('nextTick')) {
      return
    }
  }
fxy060608's avatar
fxy060608 已提交
21 22 23
  const oldTriggerEvent = mpInstance.triggerEvent
  mpInstance.triggerEvent = function (event, ...args) {
    return oldTriggerEvent.apply(mpInstance, [customize(event), ...args])
fxy060608's avatar
fxy060608 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
  }
}

Page = function (options = {}) {
  const name = 'onLoad'
  const oldHook = options[name]
  if (!oldHook) {
    options[name] = function () {
      initTriggerEvent(this)
    }
  } else {
    options[name] = function (...args) {
      initTriggerEvent(this)
      return oldHook.apply(this, args)
    }
  }
fxy060608's avatar
fxy060608 已提交
40
  return MPPage(options)
fxy060608's avatar
fxy060608 已提交
41 42 43 44 45 46 47 48 49 50
}

const behavior = Behavior({
  created () {
    initTriggerEvent(this)
  }
})

Component = function (options = {}) {
  (options.behaviors || (options.behaviors = [])).unshift(behavior)
fxy060608's avatar
fxy060608 已提交
51
  return MPComponent(options)
fxy060608's avatar
fxy060608 已提交
52
}