Live data from Hacker News

TinyJS – Shorten JavaScript QuerySelect with $ and $$

github.com

71–80 of 94 posts

Re: TinyJS – Shorten JavaScript QuerySelect with $ and $$

#71

I've been using this for years: 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: Is reachable with: $id.thing And, since the underlying structure is just an object,…

I also put together a Proxy microlib a few years ago. I agree it's very powerful.

You can use it like:

    $('.my-elements').className = 'Important'; 
    $('.my-elements').style.color = 'Red';     
    $('.my-elements').classList.add('Another'); 


    const $ = (() => {
        function listProxy(arr) {
            return new Proxy(arr, {
                set: (t, p, v, r) => {
                    for(let x of t) {
                        x[p] = v;
                    }
                },
                get: (t, p, r) => {
                    if(t.length > 0 && t[0][p] instanceof Function) {
                        return (...args) => { Array.prototype.map.call(t, (x) => x[p](args)) };
                    } else {
                        return listProxy( Array.prototype.map.call(t, (x) => x[p]) );
                    }
                }
            })
        }

        return (sel, root) => {
            if(root === undefined) root = document;
            return listProxy(root.querySelectorAll(sel));
        }
    })();
demo: https://codepen.io/anon/pen/RxGgNR

Re: TinyJS – Shorten JavaScript QuerySelect with $ and $$

#72

I've been using this for years: 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: Is reachable with: $id.thing And, since the underlying structure is just an object,…

Does caching help? If so, shouldn't getElementById do the same thing under the hood?

It used to more in the past.

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.

Re: TinyJS – Shorten JavaScript QuerySelect with $ and $$

#73

I've been using this for years: 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: Is reachable with: $id.thing And, since the underlying structure is just an object,…

Why cache? I expect that getElementById will be efficient enough on its own.

Re: TinyJS – Shorten JavaScript QuerySelect with $ and $$

#74

This is the whole code: (() => { const assignDeep = (elm, props) => Object.entries(props).forEach(([key, value]) => typeof value === 'object' ? assignDeep(elm[key], value) : Object.assign(elm, {[key]: value})) const tagNames = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'd…

Why do you pollute the global scope with all this crap? It's 2024, dude. Just make an ESM module.

Re: TinyJS – Shorten JavaScript QuerySelect with $ and $$

#75

I've been using this for years: 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: Is reachable with: $id.thing And, since the underlying structure is just an object,…

This is awesome! Proxies can be so cool. I made this proxy many years ago for tracking stats/buffs/debuffs/gear for game things.

https://github.com/MrLeap/Statsi

Re: TinyJS – Shorten JavaScript QuerySelect with $ and $$

#77
post #65

Earlier quoted context omitted.

Element IDs are automatically attached to the window object document.addEventListener('DOMContentLoaded', () => { window.thing.innerHTML = 'Hello, World!'; });

That's (much) slower and has surprising edge cases: https://news.ycombinator.com/item?id=32997636

[deleted]

Re: TinyJS – Shorten JavaScript QuerySelect with $ and $$

#78
post #71

I've been using this for years: 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: Is reachable with: $id.thing And, since the underlying structure is just an object,…

I also put together a Proxy microlib a few years ago. I agree it's very powerful. You can use it like: $('.my-elements').className = 'Important'; $('.my-elements').style.color = 'Red'; $('.my-elements').classList.add('Another'); const $ = (() => { function listProxy(arr) { return new Proxy(arr, { set: (t, p, v, r) => { for(let x of t) { x[p] = v; } }, get: (t, p, r) => { if(t.length > 0 && t[0][p] instanceof Function…

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().

Re: TinyJS – Shorten JavaScript QuerySelect with $ and $$

#79
post #62

Earlier quoted context omitted.

What's the point of the rest of the code? Looks useless.

Looks difficult. I have no clue what I'm reading there tbh.

It's creating global helper funcs for creating elements. E.g. `a(...)` for an anchor

Re: TinyJS – Shorten JavaScript QuerySelect with $ and $$

#80

Earlier quoted context omitted.

I'm quite fond of a little helper like so: createElement({ className: 'p-2 flex justify-end', contents: createElement({ tag: 'img', src: '/os-logo-maps.svg' }), }); I got the idea from Lea Verou's blissfuljs. When you're creating a bunch of nested elements it comes in handy.

That’s React without the JSX sugar.

The idea is older than react and react contains much more cruft (both wanted and unwanted).
Post reply on HN