-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
31 lines (27 loc) · 978 Bytes
/
index.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
function dataBinding(initialData) {
const render = (elem, value) => elem.innerHTML = value;
const renderInBindedElements = (prop, value) => {
const bindedElems = document.querySelectorAll(`[data-bind-${prop}]`);
bindedElems.forEach(elem => render(elem, value));
};
const state = new Proxy(initialData, {
set(obj, prop, value) {
obj[prop] = value;
renderInBindedElements(prop, value);
}
});
Object.keys(initialData).forEach(key => {
renderInBindedElements(key, initialData[key]);
});
return state;
}
// Get instance of binded object with passed in initial values
let state = dataBinding({
name: 'Some name',
name2: 'Second Name',
something: 'random text',
anythingElse: 123
});
// Now if you update something in state, the changes will be reflected to template
state.name = 'Some other Name';
state.something = 'another random text';