DEV Community

Cover image for Two-way data binding in vanilla JS (POC)

Two-way data binding in vanilla JS (POC)

Francesco Esposito on February 02, 2019

As Front-end Engineers we mostly use libraries and/or frameworks to develop and maintain complex web apps, but what there is under the hood? Do you...
Collapse
 
tormodvm profile image
Tormod Vold Mikkelsen

Very helpful! Thanks a lot. :)
You have a typo in there:

    const state = createState({
      name = 'Francesco'
      title = 'Front-end Engineer'
    });

Should be

    const state = createState({
      name: 'Francesco',
      title: 'Front-end Engineer'
    });
Collapse
 
anujjaryal profile image
Anuj jaryal

How extend it to include array of elements, like
I have in DOM:



< input name=product[1][quantity]>
and so on...

Collapse
 
phoinixi profile image
Francesco Esposito

I would say that this is mostly a Proof of concept to show a possible implementation of two-way data binding, but for an app I would advice you to use a library (e.g. React)

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);

Collapse
 
itsjzt profile image
Saurabh Sharma

Helpful article, thanks 😋

Collapse
 
ajayadav09 profile image
ajayadav09

Great will try this on smaller projects.

Collapse
 
mervinsv profile image
Mervin

Thanks for this info!

Maybe the next one would be a two-way binding for a list.