-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinding.html
More file actions
89 lines (76 loc) · 2.17 KB
/
Copy pathbinding.html
File metadata and controls
89 lines (76 loc) · 2.17 KB
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="currency-converter.js"></script>
<title>Document</title>
</head>
<body>
<currency-converter></currency-converter>
</body>
<script>
//two-way binding
function bindInputToProperty(input, obj, prop, effect) {
// Set the initial value
input.value = obj[prop];
// Listen for changes on the input element and update the object
input.addEventListener("input", (e) => {
obj[prop] = e.target.value;
});
// Create a private field to store the value
obj[`_${prop}`] = obj[prop];
Object.defineProperty(obj, prop, {
set(value) {
obj[`_${prop}`] = value;
input.value = obj[prop];
effect(value);
},
get() {
return obj[`_${prop}`];
},
});
}
//one-way binding
function bindElementToProperty(input, obj, prop, effect) {
// Set the initial value
input.innerHTML = obj[prop];
// Create a private field to store the value
obj[`_${prop}`] = obj[prop];
Object.defineProperty(obj, prop, {
set(value) {
obj[`_${prop}`] = value;
input.innerHTML = obj[prop];
effect(value);
},
get() {
return obj[`_${prop}`];
},
});
}
const converterComponent =
document.getElementsByTagName("currency-converter")[0];
// Your component starts here
let data = { amount: 1, rate: 1.81 };
let input = converterComponent.inputElement;
let propName = "amount";
bindInputToProperty(
converterComponent.inputElement,
data,
"amount",
(v) => {
updateResult();
}
);
bindElementToProperty(converterComponent.rateElement, data, "rate", (v) => {
updateResult();
});
updateResult();
converterComponent.onRateUpdateCallback = () => {
data.rate = (1.8 + Math.random() / 10).toFixed(2);
};
function updateResult() {
converterComponent.resultInnerHtml = data.amount * data.rate;
}
</script>
</html>