-
Notifications
You must be signed in to change notification settings - Fork 0
/
singleton.html
124 lines (122 loc) · 3.04 KB
/
singleton.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>单例模式</title>
<style>
.button{
height: 34px;
line-height: 34px;
text-align: center;
color: #000;
width: 80px;
margin: 10px;
cursor: pointer;
display: inline-block;
border: 1px solid #575757;
}
.hide{
display: none;
}
</style>
</head>
<body>
<div class="wrap">
<div class="content">
<div id="open" class="button">
open
</div>
<div id="hide" class="button">
hide
</div>
<div id="delete" class="button">
delete
</div>
</div>
</div>
<script>
let Modal = function(id, html) {
this.html = html
this.id = id
this.domInstance = null
this.open = false
};
Modal.prototype.create = function() {
if (!this.open) {
console.log('create dom instance')
// 创建DOM
const modal = document.createElement("div");
modal.innerHTML = this.html;
modal.id = this.id;
this.domInstance = modal
document.body.appendChild(modal);
setTimeout(function() {
modal.classList.add("show");
}, 0);
this.open = true;
}
}
Modal.prototype.hide = function() {
if (this.open) {
this.domInstance.classList.add("hide");
this.open = false
}
}
Modal.prototype.delete = function() {
// 删除延迟
let time = this.open ? 0 : 200
if (this.domInstance) {
setTimeout(() => {
document.body.removeChild(this.domInstance);
this.domInstance = null
}, time)
}
}
// 创建一个Modal实例
let createInstance = (function() {
/*
使用闭包来保存当前的实例,这个是单例模式中至关重要的一个部分。
*/
let instance = null
return () => {
console.log(instance)
// debugger 用
if (instance) {
console.log('已经存在实例了')
}
// 判断当前时候还存在以一个实例,如果存在就返回这个实例,不存在的话就生成一个
return instance || (instance = new Modal("modal", `这是一个单例的模态框`));
}
})()
// 操作源对象
let operate = {
setModal: null,
// create && open
open() {
this.setModal = createInstance();
this.setModal.create();
},
// hide
hide () {
this.setModal ? this.setModal.hide() : "";
},
//hide && delete
delete() {
this.setModal ? this.setModal.delete() : "";
}
}
// test
document.getElementById('open').onclick = function () {
operate.open();
}
document.getElementById('hide').onclick = function () {
operate.hide()
}
document.getElementById('delete').onclick = function () {
operate.delete()
}
</script>
</body>
</html>