create-media-query-observer.js 1.2 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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
import createCallbacks from 'uni-helpers/callbacks'
import {
  getCurrentPageVm
} from '../../platform'

const createMediaQueryObserverCallbacks = createCallbacks('requestMediaQueryObserver')

class ServiceMediaQueryObserver {
  constructor (component, options) {
    this.pageId = component.$page && component.$page.id
    this.component = component._$id || component // app-plus 平台传输_$id
    this.options = options
  }

  observe (options, callback) {
    if (typeof callback !== 'function') {
      return
    }
    this.options = options

    this.reqId = createMediaQueryObserverCallbacks.push(callback)

    UniServiceJSBridge.publishHandler('requestMediaQueryObserver', {
      reqId: this.reqId,
      component: this.component,
      options: this.options
    })
  }

  disconnect () {
    UniServiceJSBridge.publishHandler('destroyMediaQueryObserver', {
      reqId: this.reqId
    })
  }
}

export function createMediaQueryObserver (context, options) {
  if (!context._isVue) {
    options = context
    context = null
  }
  if (context) {
    return new ServiceMediaQueryObserver(context, options)
  }
  return new ServiceMediaQueryObserver(getCurrentPageVm('createMediaQueryObserver'), options)
}