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?
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]; };
[data-model=${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);
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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?
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);