lundi 25 juillet 2022

Implementing reactivity in vanilla JS

I use vanilla JS on webpages, and I'm trying to understand whether my design pattern is correctly implementing the principle of reactivity.

(Note: I'm not referring to the library React -- though I'm happy for answers to draw on features or strategies of such libraries).

My basic understanding is that you have some data which acts as your single source of truth, you listen for changes, and when that data changes, your page|app|component re-renders to reflect that.

Here's a simplified version of what I do, with questions after.

Let's say I have my single source of truth:

let data = {}
data.someContent = 'Hello World'
data.color = 'red'

and my app's markup in a template string for dynamic rendering:

function template(data) {
  return `
  <div id="app" style="color:${data.color}">${data.someContent}</div>
`
}
// assume there are also plain HTML inputs on the page, outside of what gets re-rendered.   

a function that renders based on the data:

function render(data) {
  document.getElementById('app').innerHtml = template(data)
} 

then, for the equivalent of reactivity from client-side updates:

document.addEventListener('input', (e) => {
  data[e.id] = e.target.value // update data to reflect input
  render(data) // re-render based on new data
})

and from server-side updates:

function fetchDataAndReRender() {
  data.propToUpdate = // fetch data from server
  render(data) // again, re-render
return
}

So, we've got the single source of truth and re-rendering based on data updates.

  • Is there another pillar to this, beyond the trio of data, listeners, and rendering?
  • I understand that libraries usually listen directly to changes on the data object, e.g. via Proxies. It seems like the only advantage to that is avoiding manually calling render(). Is that correct?

Aucun commentaire:

Enregistrer un commentaire