【源碼】weex web 組件注入分析

Weex Web 組件注冊

進行 module 的定義

import Alert from './alert'
import _css from './style'

const modal = {
  alert: function (config, callback) {
    config.callback = function () {
      callback && callback()
    }
    new Alert(config).show()
  },
  ...
}
export default {
  init: function (Weex) {
    ...
    Weex.registerModule('modal', modal)
  }
}

方法 registerModule 定義

創建新的對象, 然后將 mdule 上對應的ownProperty 定義的方法都代理到新的對象上

registerApiModule (name, module, meta) {
    if (!weexModules[name]) {
      weexModules[name] = {}
    }
    for (const key in module) {
      if (module.hasOwnProperty(key)) {
        weexModules[name][key] = function () {
          const called = weex._meta.apiCalled
          if (!called[name]) {
            called[name] = {}
          }
          const calledMod = called[name]
          if (!calledMod[key]) {
            calledMod[key] = 0
          }
          calledMod[key]++
          return module[key].apply(weex, arguments)
        }
      }
    }

調用定義方法

image

callback 函數調用

[圖片上傳失敗...(image-b5f8cd-1552542830883)]

組件 Alert 構造

會引用基類 modal 文件,然后在構造函數中執行Modal.call(this)

import Modal from './modal',

export default function Alert (config) {
  this.msg = config.message || ''
  this.callback = config.callback
  this.okTitle = config.okTitle || 'OK'
  
  Modal.call(this)
  
  this.node.classList.add('weex-alert')
}
Alert.prototype = Object.create(Modal.prototype)

組件 Alert函數擴展

會實現具體的渲染函數 createNodeContent 來完成具體的頁面渲染.

createElement( TagName ) : 會創建出對應的 html 元素

createTextNode( Text ) : 創建對應的文本節點

Alert.prototype.createNodeContent = function () {
  const content = document.createElement('div')
  content.classList.add(CONTENT_CLASS)
  this.node.appendChild(content)

  const msg = document.createElement('div')
  msg.classList.add(MSG_CLASS)
  msg.appendChild(document.createTextNode(this.msg))
  content.appendChild(msg)
  ...
}

通過 bindEvents() 進行點擊事件的綁定和注冊

Alert.prototype.bindEvents = function () {
  Modal.prototype.bindEvents.call(this)
  const button = this.node.querySelector('.' + BUTTON_CLASS)
  button.addEventListener('click', function () {
    this.destroy()
    this.callback && this.callback()
  }.bind(this))
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容