my favourite javascript framework is javascript
Joshua HawxwellSometimes to say that you “wrote” a piece of code feels wrong, it can feel more like you discovered it. Or re-discovered it anyhow, because it probably exists in many other places in slight variations.
function h (tag, attrs = {}, children = []) {
const el = document.createElement(tag)
for (const attr in attrs) {
if (attr.startsWith('on')) {
el[attr] = e => attrs[attr](el, e)
} else {
el.setAttribute(attr, attrs[attr])
}
}
for (const child of children) {
if (typeof child === 'string') {
el.appendChild(document.createTextNode(child))
} else {
el.appendChild(child)
}
}
return el
}
Which I wrote while updating alexandria as,
- I wrote the original in 2014;
- it used jQuery;
- it used jQuery plugins;
- sometimes I can’t be bothered deciding on which framework to use / which will age best.
It captures what I like about Elm, but in a slightly uglier way.
h('input', {
class: 'title',
value: data.title,
onblur: me => this.setTitle(me.value),
onkeypress: (me, e) => {
if (e.keyCode === 13) me.blur()
}
})
Of course I’m not saying anyone should go out and use this as the core idea of
their applications, especially if writing as part of a team. Using something
with a bit more structure is obviously needed to prevent large apps
becoming soup; this is a 300ish line app that essentially draws a <table>
. And
I’m pretty sure rebuilding rows when filtering or sorting isn’t the most
efficient way of programming against the DOM, though I doubt it is too bad for
the size of table I have.
What I’m trying to say is, with all of us only using frameworks we can sometimes forget how nice plain ol’ JavaScript is in the year 2019.