单例模式-自定义弹窗

分析

在我们return instance之前到if语句之间,那一段代码是可以执行的。
考虑到公用一些属性以及状态,我们可以使用闭包的方式来解决。将闭包设置为立即执行函数,那么在函数加载完成之后,公共的属性以及方法就可以访问到,我们只需要操控一些方法去更改这些属性即可。

核心代码

<script>
  const Tip = (function () {
    class Tip {
      constructor() {
        this.ele = document.createElement('div')
        this.ele.className = 'box'
        this.callback = function () {
        }
        document.body.appendChild(this.ele)
        this.bindEvent()
      }
      // 设置内容及样式
      setTip (option, cb) {
        this.ele.innerHTML = `
      <div class="top">${option.title}</div>
      <div class="content">
        <p>${option.txt}</p>
      </div>
      <div class="btn">
        <button class="cancel">取消</button><button class="ok">确认</button>
      </div>
      `
        this.ele.style.display = 'block'
        document.querySelector('.top').style.backgroundColor = option.color
      }
      // 2. 绑定各种事件
      bindEvent (e) {
        this.ele.addEventListener('click', e => {
          const target = e.target
          if (target.className === 'top') {
            this.ele.style.display = 'none'
          }
          if (target.className === 'cancel') {

            this.callback(false)
            // console.log(this.callback)
            this.ele.style.display = 'none'
          }
          if (target.className === 'ok') {
            // alert('点击了ok')
            this.ele.style.display = 'none'
            this.callback(true)
          }
        })
      }
    }
    this.instance = null
    return function singleTon (option, cb) {
      // 实例化只有第一次执行
      if (!instance) instance = new Tip()
      // 底下的代码每次都会执行

      instance.callback = cb || function () { }
      instance.setTip(option, cb)
      return instance
    }
  })()
  new Tip({
    title: '失败',
    type: 'success',
    color: 'red',
    txt: '添加失败'
  }, res => { console.log('00000', res) })
  // new Tip('error', '请求失败')
</script>

完整代码

单例模式-自定义弹窗

posted @ 2023-03-15 14:21  含若飞  阅读(31)  评论(0编辑  收藏  举报