The return of Rails UJS¶
Unobtrusive Javascript is an easy way to added single page app like features to HTML links and form tags. Its been a staple feature since Rails 6, but will sunset with the release of Rails 8 in favor of Hotwire and friends.
Superglue puts UJS back in the forefront and embues it with superpowers (curtesy of props_template) that makes building SPA-like functionality easy and consistent.
Want to reload a shopping cart?
Or maybe load a modal efficiently when the next page has one?
With Superglue, there is just one concept. No need for the complexity of Stimulus controllers, Turbo Streams, or Turbo Frames.
Navigating with UJS¶
Superglue operates like a multipage application. In other to transition to the
next page without reloading you'll need to use UJS attributes data-sg-remote
or data-sg-visit
.
data-sg-visit
¶
Use data-sg-visit
when you want to navigate to the next page and update the
address bar without reloading.
In the above example, when the link is clicked, Superglue will intercept the click,
make a request for /posts/new.json
, swap your page component, and pass the payload.
Note
You are not able to specify the HTTP method used in a UJS link. This is intentional. If you want to create a link that can support different HTML methods, create a form component that looks like a link and use props generated from form_props
You can also use data-sg-visit
on forms:
data-sg-placeholder
¶
A companion attribute for use with data-sg-visit
. By specifiying a
placeholder, superglue will take the page props at that placeholder and
optimistically copies it as the page props for the next page while a request is
made.
It's for cases when you know with certainty how the next page is going to look like, but you want to selectively fetch just the content you need to make an update without loading the entirety of the next page. For example, modals, tabs, notifications, etc.
<a href="/posts/new?props_at=data.modal" data-sg-visit data-sg-placeholder="/posts">
Create Post
</a>
data-sg-remote
¶
Use data-sg-remote
when you want to update parts of the current page without
reloading the screen. You'd can use this with props_template's [digging]
to selectively load content.
You can also use data-sg-remote
on forms.