Disconnect/reconnect controllers according to viewport size

I had a use case today whereby I needed particular controllers to only be connected above a specified viewport size (desktop only, basically).

Ultimately I achieved this by having some separate javascript with a media query listener that, when triggered, filtered the controllers from the DOM and removed/added their data-controller attributes as necessary.

The only immediate issue this caused was that rather than use this.somethingTarget in the disconnect function, I had to use this.element.querySelector(...).

I’d be keen to know if anyone has any cleaner ways of doing this? It’d be nice if there was a way to connect and disconnect controllers in a cleaner, more practical way from within the controllers themselves (which wouldn’t be possible with disconnect I guess, but maybe a method to conditionally detach/reattach a controller).

Maybe a bit of an edge case though…shrug

maybe not exactly what you are looking for but the resizeObserver API could maybe help here.

IU have package this into a mixin you can add to you stimuluse controller to get a new resize lifecycle event when you component is resized

1 Like