forked from kkdashu/virtual-dom
-
Notifications
You must be signed in to change notification settings - Fork 1
/
modules.js
79 lines (71 loc) · 1.73 KB
/
modules.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
function addStyles(vnode) {
if (vnode && vnode.data && vnode.data.style) {
for (let k in vnode.data.style) {
vnode.elm.style[k] = vnode.data.style[k];
}
}
}
function removeStyles(vnode) {
if (vnode && vnode.data &&vnode.data.style) {
for (let k in vnode.data.style) {
if (vnode.elm.style[k]) {
vnode.elm.style[k] = '';
}
}
}
}
function updateStyles(oldVnode, newVnode) {
const oldStyle = oldVnode && oldVnode.data.style;
const newStyle = newVnode && newVnode.data.style;
if (oldStyle === newStyle) return;
if (!oldVnode || !oldStyle) {
addStyles(newVnode);
} else if (!newStyle) {
removeStyles(newVnode);
} else {
removeStyles(oldVnode);
addStyles(newVnode);
}
}
function updateEvents(oldVnode, newVnode) {
if (!oldVnode || !newVnode) return;
const oldKeys = getEventKeys(oldVnode);
let newKeys = getEventKeys(newVnode);
// 清除没有的事件
oldKeys.forEach(k => {
oldVnode.elm.removeEventListener(getEventName(k), oldVnode.data[k]);
});
newKeys.forEach(k => {
newVnode.elm.addEventListener(getEventName(k), newVnode.data[k]);
});
}
function addEvents(vnode) {
const keys = getEventKeys(vnode);
keys.forEach(k => {
vnode.elm.addEventListener(getEventName(k), vnode.data[k]);
});
}
function getEventKeys(vnode) {
let keys = [];
for (let k in vnode&&vnode.data) {
if (k.startsWith('on')) {
keys.push(k);
}
}
return keys;
}
function getEventName(key) {
return key.replace('on', '').toLowerCase();
}
function updateProps(oldVnode, newVnode) {
updateStyles(oldVnode, newVnode);
updateEvents(oldVnode, newVnode);
}
function addProps(vnode) {
addEvents(vnode);
addStyles(vnode);
}
export {
updateProps,
addProps
}