美文网首页让前端飞
【源码】weex web 组件注入分析

【源码】weex web 组件注入分析

作者: 周俊devin | 来源:发表于2019-03-14 13:54 被阅读0次

    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))
    }
    

    相关文章

      网友评论

        本文标题:【源码】weex web 组件注入分析

        本文链接:https://www.haomeiwen.com/subject/zcvqmqtx.html