Skip to content

Commit 6f5fdb7

Browse files
committed
Move updateDomProperties to dom-utils
1 parent 8eb7ffd commit 6f5fdb7

File tree

2 files changed

+29
-12
lines changed

2 files changed

+29
-12
lines changed

src/dom-utils.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
export function updateDomProperties(dom, prevProps, nextProps) {
2+
const isEvent = name => name.startsWith("on");
3+
const isAttribute = name => !isEvent(name) && name != "children";
4+
5+
// Remove event listeners
6+
Object.keys(prevProps).filter(isEvent).forEach(name => {
7+
const eventType = name.toLowerCase().substring(2);
8+
dom.removeEventListener(eventType, prevProps[name]);
9+
});
10+
11+
// Remove attributes
12+
Object.keys(prevProps).filter(isAttribute).forEach(name => {
13+
dom[name] = null;
14+
});
15+
16+
// Set attributes
17+
Object.keys(nextProps).filter(isAttribute).forEach(name => {
18+
dom[name] = nextProps[name];
19+
});
20+
21+
// Add event listeners
22+
Object.keys(nextProps).filter(isEvent).forEach(name => {
23+
const eventType = name.toLowerCase().substring(2);
24+
dom.addEventListener(eventType, nextProps[name]);
25+
});
26+
}

src/reconciler.js

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { updateDomProperties } from "./dom-utils";
2+
13
let rootInstance = null;
24

35
export function render(element, container) {
@@ -27,18 +29,7 @@ function instantiate(element) {
2729
? document.createTextNode("")
2830
: document.createElement(type);
2931

30-
// Add event listeners
31-
const isListener = name => name.startsWith("on");
32-
Object.keys(props).filter(isListener).forEach(name => {
33-
const eventType = name.toLowerCase().substring(2);
34-
dom.addEventListener(eventType, props[name]);
35-
});
36-
37-
// Set properties
38-
const isAttribute = name => !isListener(name) && name != "children";
39-
Object.keys(props).filter(isAttribute).forEach(name => {
40-
dom[name] = props[name];
41-
});
32+
updateDomProperties(dom, [], props);
4233

4334
// Instantiate and append children
4435
const childElements = props.children || [];

0 commit comments

Comments
 (0)