单例模式实现弹窗

Author Avatar
Silas Shen 4月 04, 2018

单例模式

一个类仅有一个实例,并提供一个全局的访问点 => 业务场景 账号注册时,一个号码重复注册会提示错误信息

步骤

  1. 获取一个DOM对象
var $ = function(id) {
    return typeof id === 'string' ? document.getElementById(id) : id;
};
  1. 弹框构造函数
var Modal = function(id,html) {
    this.html = html;
    this.id = id;
    this.open = false; 
};
  1. open方法
Modal.prototype.create = function() {
    if (!this.open) {
        var modal = document.createElement('div');
        
        modal.innerHTML = this.html;
        modal.id = this.id;
        document.body.appendChild(modal);
     
        setTimeout(function() {
            modal.classList.add('show');
        },0);

        this.open = true;
    }
};
  1. close方法
Modal.prototype.delete = function() {
    if (this.open) {
        var modal = $(this.id);

        modal.calssList.add('hide');
        setTimeout(function() {
            document.body.removeChild(modal);
        },200);

        this.open = false;
    }
};
  1. 创建实例
var createIntance = (function() {
    var instance;
    return function() {
        return instance || (instance = new Modal('modal','这是一个弹窗'))
    }
}) ();
  1. 按钮操作
var operate = {
    setModal: null,
    open: function() {
        this.setModal = createIntance();
        this.setModal.create();
    },
    delete: function() {
        this.setModal ? this.setModal.delete() : '';
    }
};
  1. 绑定事件
$('open').onclick = function() {
    operate.open();
};
$('delete').onclick = function() {
    oprate.delete();
}