Details

Playing with JavaScript Proxy to sync JS and the DOM

The inherent disconnect between the DOM state and JavaScript has spawned a whole series of solutions and frameworks with many benefits and tradeoffs.

I was playing with JavaScript Proxy recently, and I thought it would be handy to use Proxy to maintain data binding between the DOM and JavaScript. In this case a generic changePerson() function responds to the user's input on the DOM and updates the JavaScript person object. Proxy sees (actually makes) those changes to the person object and updates the DOM accordingly. There's just one change handler function here, one person object, and one person Proxy.

This method means you simply update the JavaScript object and the DOM is updated automatically. You could also use Proxy to validate input, log important information, and etc.

Depending on your use case this could be pretty handy, or not.

While they don't use Proxy to update the DOM, this was inspired by the FrontEnd Master's course A Tour of JavaScript & React Patterns.

This page uses Simple.css for styling.

Input changes the person object

Output from proxy to the DOM

Name:
Age:
Email:

JavaScript:

        
const person = {
    name: null,
    age: null,
    email: null
};
        
const personProxy = new Proxy(person, {
    get: (target, prop) => {
        console.log(`The value of ${prop} is ${target[prop]}`);
        return target[prop];
    },
    set: (target, prop, value) => {
        console.log(`Changed ${prop} from ${target[prop]} to ${value}`);
        document.getElementById(prop).innerText = value
        target[prop] = value;
        return true;
    },
});
        
function changePerson(event) {
    let property = event.target.name
    personProxy[property] = event.target.value
}