vdom-sync.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 24 25 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
import {
  PAGE_CREATED
} from '../../../constants'

import {
  removeWebviewUIEvent,
  registerWebviewUIEvent
} from '../subscribe-handlers'

export class VDomSync {
  constructor (pageId, pagePath) {
    this.pageId = pageId
    this.pagePath = pagePath
    this.batchData = []
    this.vms = Object.create(null)
    this.initialized = false
    // 事件
    this.handlers = Object.create(null)

    this._init()
  }

  _init () {
    registerWebviewUIEvent(this.pageId, (cid, nid, event) => {
      console.log(`[EVENT]`, cid, nid, event)
      if (
        this.handlers[cid] &&
        this.handlers[cid][nid] &&
        this.handlers[cid][nid][event.type]
      ) {
        this.handlers[cid][nid][event.type].forEach(handler => {
          handler(event)
        })
      }
    })
  }

  getVm (id) {
    return this.vms[id]
  }

  addVm (vm) {
    this.vms[vm._$id] = vm
  }

  removeVm (vm) {
    delete this.vms[vm._$id]
  }

  addEvent (cid, nid, name, handler) {
    const cHandlers = this.handlers[cid] || (this.handlers[cid] = Object.create(null))
    const nHandlers = cHandlers[nid] || (cHandlers[nid] = Object.create(null));
    (nHandlers[name] || (nHandlers[name] = [])).push(handler)
  }

  removeEvent (cid, nid, name, handler) {
    const cHandlers = this.handlers[cid] || (this.handlers[cid] = Object.create(null))
    const nHandlers = cHandlers[nid] || (cHandlers[nid] = Object.create(null))
    const eHandlers = nHandlers[name]
    if (Array.isArray(eHandlers)) {
      const index = eHandlers.indexOf(handler)
      if (index !== -1) {
        eHandlers.splice(index, 1)
      }
    }
  }

  push (type, nodeId, data) {
    this.batchData.push([type, [nodeId, data]])
  }

  flush () {
    if (!this.initialized) {
      this.initialized = true
fxy060608's avatar
fxy060608 已提交
75
      this.batchData.push([PAGE_CREATED, [this.pageId, this.pagePath]])
fxy060608's avatar
init v3  
fxy060608 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
    }
    if (this.batchData.length) {
      UniServiceJSBridge.publishHandler('vdSync', {
        data: this.batchData,
        options: {
          timestamp: Date.now()
        }
      }, [this.pageId])
      this.batchData.length = 0
    }
  }

  destroy () {
    this.batchData.length = 0
    this.vms = Object.create(null)
    this.initialized = false
    this.handlers = Object.create(null)
    removeWebviewUIEvent(this.pageId)
  }
}