const $id = new Proxy({}, {
// get element from cache, or from DOM
get: (tgt, k, r) => (tgt[k] || ((r = document.getElementById(k)) && (tgt[k] = r))),
// prevent programming errors
set: () => $throw(`Attempt to overwrite id cache key!`)
});
It's nice to be able to refer to elements by property name, so:
<div id="thing"></div>
Is reachable with:
$id.thing
And, since the underlying structure is just an object, you can still enumerate it with Object.keys, which can sometimes be a useful debugging aid and general catalog of accessed elements.
Anyways.. Proxy is a wildly underappreciated and used class in JavaScript.
I built a Proxy-based microlib for making fluent REST calls just on a lark a couple years ago. It was never anything production-ready, but it was so handy that I used it in all of my JS projects until I moved away from webdev. The API was basically:
const api = new Proxy({route: baseRoute}, handler); // handler is the microlib's export
const result = await api.get.some.route.invoke(); // GET {baseRoute}/some/route
invoke() is just how it finally fires the call. I didn't feel like spending too much time making it automatic, the benefits just weren't large enough to justify compared to just calling invoke().
The native call does usually include a cache and will use it optimistically; however, the strategies around invalidating this cache are varied and some surprisingly basic DOM actions can trigger it. Then browsers usually fallback to the full DOM query case.
The cache eliminates this variability, which prior to flexbox, could be very useful in highly nested site designs particularly in mobile contexts.
My fault, I tend to "rapid fire" sometimes. Yours was next to another reply on the identical subject and that caused me to mistake the meaning of the comma in your sentence.
Reading it more slowly, I see it now, and, thank you!
A call to `$id.toString` actually yields the native unbound function whether or not there is such an element on the page. So get is not invoked in this case.
Anyways.. Proxy is a wildly underappreciated and used class in JavaScript.