by rembrant · 4y ago · 0 comments
const { container, heading } = divs;
and then container is assigned to an HTMLDivElement <div class="container"></div> and the same type of thing for heading because divs is a proxy for an object with getters that can figure out the name of the variable you are destructing into and create a new element with that class name. It saves a lot of code. const container = document.createElement('div');
container.className = 'container';
const heading = document.createElement('div');
heading.className = 'heading';
The other way you can create elements is just with a common: const heading = span({ title: artName, innerText: whatever });
etc so my web components have less code than react components, and run at native hand-written speed. Proxies aren't actually slow despite what I had read via google. In fact, the proxy is a bit faster than the naive implementation because it caches the divs and cloneNodes them.For the second way of creating elements (the span example), instead of creating a function for every html or svg tag, I use another proxy so you can do:
const { span, h3 } = html;
and it creates the span and h3 function dynamically. This saves me writing all the code for each tag and allows new tags to be used without me having to add them to the library.For folks wondering, here's how it would work:
const htmlClasses = new Proxy({}, {
get: (target, prop, receiver) => document.querySelector('.' + prop)
});
// Get element with class pagetop
htmlClasses.pagetop;
const htmlNodes = new Proxy({}, {
get: (target, prop, receiver) => document.querySelectorAll(prop)
});
// Get all h3s
htmlNodes.h3;
You can run this on hackernews to see it work.Anyway, I just think it is cool kind of for the same reason it is misleading :)
You can do a loop like:
for (let i = 0; i < 100; i++) {
const { cool } = divs;
cool.innerText = new Date();
document.body.append(cool);
}
and cool is actually a new div each time, even though you would think it was the same cool from divs (divs.cool). It also caches the div, so it is faster than even if you wrote the manual version with createElement.I could get rid of it, because my other approach to element creation would is:
const cool = div({ className: 'cool' });
which isn't too bad, but when I have a lot of divs, it is just nicer to do: const {
root,
headingContainer,
userContainer } = divs;
Also, yeah, it actually creates hyphened classes. so headingContainer goes to .heading-container. That is just how I work and so it is a convention.A never ending well of new divs that have the class name of the variable name