subscribe-handlers.js 2.3 KB
Newer Older
fxy060608's avatar
init v3  
fxy060608 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
import {
  WEBVIEW_READY,
  WEBVIEW_UI_EVENT
} from '../../constants'

import {
  preloadWebview,
  setPreloadWebview,
  consumeWebviewReady
} from './webview'

import {
  registerPlusMessage
} from './plus-message'

import {
  perf
} from './perf'

function onWebviewReady (data, pageId) {
  const isLaunchWebview = pageId === '1'
  if (isLaunchWebview) { // 首页
    setPreloadWebview(plus.webview.getLaunchWebview())
fxy060608's avatar
fxy060608 已提交
24 25
  } else if (!preloadWebview) { // preloadWebview 不存在,重新加载一下
    setPreloadWebview(plus.webview.getWebviewById(pageId))
fxy060608's avatar
init v3  
fxy060608 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 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 75 76 77 78 79 80 81 82 83
  }
  if (preloadWebview.id !== pageId) {
    return console.error(`webview[${pageId}] not found`)
  }
  preloadWebview.loaded = true // 标记已 ready

  consumeWebviewReady(pageId)

  if (isLaunchWebview) {
    const entryPagePath = '/' + __uniConfig.entryPagePath
    const routeOptions = __uniRoutes.find(route => route.path === entryPagePath)
    if (!routeOptions.meta.isNVue) { // 非 nvue 首页,需要主动跳转
      const navigateType = routeOptions.meta.isTabBar ? 'switchTab' : 'navigateTo'
      process.env.NODE_ENV !== 'production' && perf(`${entryPagePath} navigateTo`)
      return uni[navigateType]({
        url: entryPagePath
      })
    }
  }
}

const webviewUIEvents = Object.create(null)

export function registerWebviewUIEvent (pageId, callback) {
  (webviewUIEvents[pageId] || (webviewUIEvents[pageId] = [])).push(callback)
}

export function removeWebviewUIEvent (pageId) {
  delete webviewUIEvents[pageId]
}

function onWebviewUIEvent ({
  data,
  options
}, pageId) {
  const {
    cid,
    nid
  } = options
  const handlers = webviewUIEvents[pageId]
  if (Array.isArray(handlers)) {
    handlers.forEach(handler => {
      handler(cid, nid, data)
    })
  } else {
    console.error(`events[${pageId}] not found`)
  }
}

export function initSubscribeHandlers () {
  const {
    subscribe,
    subscribeHandler
  } = UniServiceJSBridge

  registerPlusMessage('subscribeHandler', (data) => {
    subscribeHandler(data.type, data.data, data.pageId)
  })
fxy060608's avatar
fxy060608 已提交
84
  // TODO 检测目标 preloadWebview 是否已准备好,因为 preloadWebview 准备好时,此处代码还没执行
fxy060608's avatar
init v3  
fxy060608 已提交
85 86 87
  subscribe(WEBVIEW_READY, onWebviewReady)
  subscribe(WEBVIEW_UI_EVENT, onWebviewUIEvent)
}