JSFiddle - React, Tailwind, and code Playground
by kasheftin
HTML
<div id="root">
</div>
JavaScript
let computedFunc = null
const Observable = function (value) {
this.value = value
this.watchers = []
}
Observable.prototype.get = function () {
if (computedFunc) {
this.watch(computedFunc)
}
return this.value
}
Observable.prototype.set = function (newValue) {
this.value = newValue
this.watchers.forEach((watcher) => {
watcher(newValue)
})
}
Observable.prototype.watch = function (watcher) {
if (!this.watchers.includes(watcher)) {
this.watchers.push(watcher)
}
}
const computed = function (action) {
const result = new Observable(null)
const fn = () => {
const prevComputedFunc = computedFunc
computedFunc = fn
result.set(action())
computedFunc = prevComputedFunc
}
fn()
return result
}
const El = function (el) {
this.el = el
}
El.prototype.append = function (el) {
if (el instanceof El) {
this.el.appendChild(el.el)
} else if (typeof el === 'string') {
this.el.appendChild(new Text(el))
} else {
this.el.appendChild(el)
}
return this
}
El.prototype.on = function (eventName, func) {
this.el.addEventListener(eventName, func)
return this
}
El.prototype.bind = function (name, funcOrObservable) {
const observable = funcOrObservable instanceof Observable ? funcOrObservable : computed(funcOrObservable)
if (name === 'value') {
this.on('input', (e) => {
observable.set(e.target.value)
})
}
observable.watch((value) => {
this.el[name] = value
})
this.el[name] = observable.get()
return this
}
const create = function (selector) {
const el = document.createElement(selector)
return new El(el)
}
const a = new Observable('text')
const c = new Observable(false)
const b = computed(() => {
if (c.get()) {
return a.get() + ' ' + a.get()
} else {
return 'c is turned off'
}
})
const input = create('input').bind('value', a)
const h1 = create('h1').bind('innerText', b)
const button = create('button')
.bind('innerText', () => c.get() ? 'On' : 'Off')
...