-
Notifications
You must be signed in to change notification settings - Fork 0
/
module_pattern.html
105 lines (74 loc) · 2.61 KB
/
module_pattern.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
<!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>Document</title>
</head>
<body style="color:#1A202C; margin: 2rem;">
<h1>Javascript patterns</h1>
<ul>
<li>Basic module pattern and module revealing pattern</li>
</ul>
<h3>Basic module pattern</h3>
<pre style="font-size:16px;background: #1A202C;color:green; font-weight: 900;padding: 1rem;">
// Basic structure
(function() {
// Declare private vars and functions
return {
// Declare public vars and functions
}
})()
</pre>
<pre style="font-size:16px;background: #1A202C;color:green; font-weight: 900;padding: 1rem;">
// Standart module pattern
const UICtrl = (function() {
let text = 'Hello world'
const changeText = function() {
const element = document.querySelector('.output')
element.textContent = text
}
return {
callChangeText: function() {
changeText()
console.log(text)
}
}
})();
// Run the module method
UICtrl.callChangeText()
</pre>
<h3>Output</h3>
<div class="output" style="font-size:18px;background: #1A202C;color:green; font-weight: 900;padding: 1rem;">
<p>output</p>
</div>
<h3>Revealing module pattern</h3>
<pre style="font-size:16px;background: #1A202C;color:green; font-weight: 900;padding: 1rem;">
// Revealing module pattern
const itemCtrl = (function(){
let data = []
function addItem(item) {
data.push(item)
console.log('Item added')
}
function getItem(id) {
return data.find(item => {
return item.id === id
})
}
return {
add: addItem,
get: getItem
}
})()
itemCtrl.add({id: 1, name: 'John'})
console.log(itemCtrl.get(1))
</pre>
<h3>Output</h3>
<div class="output2" style="font-size:18px;background: #1A202C;color:green; font-weight: 900;padding: 1rem;">
<p>output</p>
</div>
<script src="module_pattern.js"></script>
</body>
</html>