JSFiddle - React, Tailwind, and code Playground
HTML
The classic:
<div id="content">…loading</div>
JavaScript
function reactive(obj, callback) {
const wrapped = {}
for (let key in obj) {
let value = obj[key]
if (typeof value === 'object') {
value = reactive(value, callback)
}
Object.defineProperty(wrapped, key, {
get: function reactiveGetter() {
return value
},
set: function reactiveGetter(newValue) {
console.log('setting value from', value, 'to', newValue)
value = newValue
callback()
}
})
}
return wrapped
}
function createComponent (obj) {
const data = obj.data || {}
const render = obj.render.bind(obj)
obj.data = reactive(data, render)
return obj
}
const component = createComponent({
el: document.getElementById('content'),
data: {
name: {
first: 'Hansi',
last: 'Hinterseer',
extras: {
title: 'Musician'
}
}
},
render: function () {
console.log('component renders', this.data)
this.el.innerHTML = `<h1>Hello ${this.data.name.extras.title} ${this.data.name.first} ${this.data.name.last}</h1>`
}
})
component.data.name.first = 'Ada'
component.data.name.last = 'Lovelace'
component.data.name.extras.title = 'Prof. Dr.'