-
Notifications
You must be signed in to change notification settings - Fork 0
/
tinhat.js
95 lines (83 loc) · 2.74 KB
/
tinhat.js
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
window.__tincan = {
reactors: [],
count: 0,
};
/// Create a reactive variable
window.thReactive = (initialValue) => {
const reactor = {
id: window.__tincan.count++,
value: initialValue,
update: function(value) {
const oldValue = this.value;
this.value = value;
this.callbacks.forEach(cb => cb(oldValue, this.value))
},
callbacks: []
}
window.__tincan.reactors.push(reactor);
return reactor;
}
/// watch for changes to a reactive variable and call its callback(s)
/// with the old and new value
window.thWatch = (reactor, callback/* fn(beforeValue, afterValue) */) => {
const index = window.__tincan.reactors.findIndex(r => r.id === reactor.id);
if(index !== -1) {
window.__tincan.reactors[index].callbacks.push(callback);
}
}
// DOM helper utilities
window.thClassAdd = (elementSelector, classList) => {
const els = document.querySelectorAll(elementSelector);
els.forEach(el => {
if(Array.isArray(classList)) {
classList.forEach(cl => {
if(!el.classList.contains(cl)) {
el.classList.add(cl);
}
})
} else {
if(!el.classList.contains(classList)) {
el.classList.add(classList)
}
}
})
}
window.thClassRemove = (elementSelector, classList) => {
if(Array.isArray(classList)) {
document.querySelectorAll(elementSelector).forEach(el => classList.forEach(cl => el.classList.remove(cl)));
} else {
document.querySelectorAll(elementSelector).forEach(el => el.classList.remove(classList));
}
}
window.thClassToggle = (elementSelector, classList) => {
const els = document.querySelectorAll(elementSelector);
els.forEach(el => {
if(Array.isArray(classList)) {
classList.forEach(cl => {
if(el.classList.contains(cl)) {
el.classList.remove(cl);
} else {
el.classList.add(cl);
}
})
} else {
if(el.classList.contains(classList)) {
el.classList.remove(classList);
} else {
el.classList.add(classList);
}
}
});
}
window.thAttributeSet = (elementSelector, attribute, value) => {
const els = document.querySelectorAll(elementSelector);
els.forEach(el => {
el.setAttribute(attribute, value)
})
}
window.thSetInner = (elementSelector, innerHtml) => {
const els = document.querySelectorAll(elementSelector);
els.forEach(el => {
el.innerHTML = innerHtml;
});
}