DEV Community

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

Collapse
 
berslucas profile image
Lucas Bersier • Edited

I like this, I didn't do anything with Proxies before.

One thing with this demo is that it will only update state.quote, with a few changes it can be generic and you can update multiple elements.

const createState = state => {
  return new Proxy(state, {
    set(target, property, value) {
      target[property] = value; 
      render(property);
    }
  });
};

const render = property => {
  document.querySelector(`[data-binding="${property}"]`).innerHTML = state[property];
};
Enter fullscreen mode Exit fullscreen mode
    <div data-binding="quote1"></div>
    <div data-binding="quote2"></div>
Enter fullscreen mode Exit fullscreen mode
state.quote1 = 'hello';
state.quote2 = 'world';
Enter fullscreen mode Exit fullscreen mode

Also, I don't see any documentation for returning in the Proxy function. Is this just a code style thing or is return true useful for something in this case?

Collapse
 
phoinixi profile image
Francesco Esposito • Edited

Thanks Lucas for your comment, if you check out the code and demo (I should maybe include that in the post) you will see that it's more generic :)
return true is necessary, otherwise, you will get an error:

developer.mozilla.org/en-US/docs/W...

Collapse
 
berslucas profile image
Lucas Bersier

Gotcha. Thanks