DEV Community

Discussion on: Two-way data binding in vanilla JS (POC)

Collapse
 
beardedbry profile image
Brian

Thanks for the article. How would you expand on this?
Unless I am understanding it wrong, It looks like the render function updates everything that has a binding. Would you make it so that it only updates the bindings that had changes?

Collapse
 
sushilkundu143 profile image
Sushil Kundu • Edited

Yes. You are right. Here is the updated code.

const createState = (state) => {
return new Proxy(state, {
set(target, property, value) {
target[property] = value; // default set behaviour
render(property); // updates the view every time the state changes
return true;
}
});
};

const state = createState({
name: '',
title: ''
});

const render = (property) => {
document.querySelector([data-model=${property}]).value = state[property];
};

const listener = (event) => {
const {type, value, dataset} = event.target;
state[dataset.model] = value;
};

document.querySelector('[data-model="name"]').addEventListener('keyup', listener);

document.querySelector('[data-model="title"]').addEventListener('keyup', listener);