Skip to content

Instantly share code, notes, and snippets.

@whaaaley
Created March 29, 2019 08:59
Show Gist options
  • Save whaaaley/e287d6842321e74216a654659bb345fe to your computer and use it in GitHub Desktop.
Save whaaaley/e287d6842321e74216a654659bb345fe to your computer and use it in GitHub Desktop.
<html>
<head>
<script>
(() => {
const voidTags = ['area', 'base', 'br', 'circle', 'col', 'ellipse',
'embed', 'img', 'input', 'line', 'link', 'mesh', 'meta', 'param',
'path','polygon','polyline','rect','source','track','wbr']
const h = (tag, data, children) => {
let attrs = ''
for (let attr in data) {
attrs += ' ' + attr + '="' + (data[attr] + '').replace(/"/g, '\\"') + '"'
}
const el = '<' + tag + attrs
if (voidTags.indexOf(tag) !== -1 && !children) {
return el + '/>'
}
const inner = Array.isArray(children)
? children.join('')
: children || ''
return el + '>' + inner + '</' + tag + '>'
}
const pocket = ({ target, actions, view, container }) => {
const handler = {
set: (obj, prop, value) => {
obj[prop] = value
document.body.innerHTML = view(obj, actions)
},
get: (obj, prop) => obj[prop]
}
const proxy = new Proxy(target, handler)
const store = {}
for (let fn in actions) {
store[fn] = data => {
actions[fn] = actions[fn](data)(proxy)
}
}
return store
}
// Userland Below
const target = {}
const actions = {
stuff: data => proxy => {
proxy.state = { loading: true }
setTimeout(() => {
proxy.state = { data, loading: true }
}, 1000)
setTimeout(() => {
console.log(proxy.state.data + 'bar')
}, 2000)
}
}
const view = (proxy, actions) => {
return h('div', {}, [
h('h1', {}, 'hello world'),
h('h1', {}, 'loading: ' + proxy.state.loading),
h('h1', {}, 'foo: ' + proxy.state.data)
])
}
const container = document.getElementById('pocket')
const main = pocket({ target, actions, view, container })
setTimeout(() => {
main.stuff('foo')
}, 2000)
})()
</script>
</head>
<body>
<div id='pocket'></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment