单例模式实现弹窗
单例模式
一个类仅有一个实例,并提供一个全局的访问点 => 业务场景 账号注册时,一个号码重复注册会提示错误信息
步骤
- 获取一个DOM对象
var $ = function(id) {
return typeof id === 'string' ? document.getElementById(id) : id;
};
- 弹框构造函数
var Modal = function(id,html) {
this.html = html;
this.id = id;
this.open = false;
};
- 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;
}
};
- 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;
}
};
- 创建实例
var createIntance = (function() {
var instance;
return function() {
return instance || (instance = new Modal('modal','这是一个弹窗'))
}
}) ();
- 按钮操作
var operate = {
setModal: null,
open: function() {
this.setModal = createIntance();
this.setModal.create();
},
delete: function() {
this.setModal ? this.setModal.delete() : '';
}
};
- 绑定事件
$('open').onclick = function() {
operate.open();
};
$('delete').onclick = function() {
oprate.delete();
}