subscribe.js 1.4 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41
import createCallbacks from 'uni-helpers/callbacks'

import {
  callPageHook
} from '../plugins/util'

function createPageEvent (eventType) {
  return function (args, pageId) {
    const pages = getCurrentPages()
    const page = pages.find(page => page.$page.id === pageId)
    if (page) {
      callPageHook(page, eventType, args)
    } else {
      console.error(`Not Found:Page[${pageId}]`)
    }
  }
}

const requestComponentInfoCallbacks = createCallbacks('requestComponentInfo')

function onRequestComponentInfo ({
  reqId,
  res
}) {
  const callback = requestComponentInfoCallbacks.pop(reqId)
  if (callback) {
    callback(res)
  }
}

const requestComponentObserverCallbacks = createCallbacks('requestComponentObserver')

function onRequestComponentObserver ({
  reqId,
  reqEnd,
  res
}) {
  const callback = requestComponentObserverCallbacks.get(reqId)
  if (callback) {
    if (reqEnd) {
      requestComponentObserverCallbacks.pop(reqId)
42
      return
fxy060608's avatar
fxy060608 已提交
43 44 45 46 47 48 49 50 51 52 53 54
    }
    callback(res)
  }
}

export default function initSubscribe (subscribe) {
  subscribe('onPageReady', createPageEvent('onReady'))
  subscribe('onPageScroll', createPageEvent('onPageScroll'))
  subscribe('onReachBottom', createPageEvent('onReachBottom'))

  subscribe('onRequestComponentInfo', onRequestComponentInfo)
  subscribe('onRequestComponentObserver', onRequestComponentObserver)
55
}