Expose isSamePage to turbo:visit events
See original GitHub issue#298 was a very welcome change, as now I can drop data: { turbo: !current_page?(thing_path) }
from links that are anchors on the current page. However, turbo:visit
events now fire for visits to anchors on the same page. I’m sure this is potentially useful in some ways, but for now, it’s meant that I’ve had to go from hooking into turbo:visit
to using turbo:before-visit
as follows:
import isEqual from "lodash.isequal"
document.addEventListener("turbo:before-visit", function (e) {
const attributes = ({ origin, pathname }) => ({ origin, pathname })
if (
!isEqual(attributes(window.location), attributes(new URL(e.detail.url)))
) {
// do things here
}
})
What I’m doing there is pulling the origin
(http://example.com
) and the pathname (/blog
, without an anchor or any query params) from the window location before the request is processed, and comparing it with those the target URL. If they’re identical, then it’s safe to say we shouldn’t do what would otherwise be triggered under turbo:visit
.
It’d be nicer to be able to, for example, do this:
document.addEventListener("turbo:visit", function (e) {
if(e.samePage) { return; }
// do things here
})
Issue Analytics
- State:
- Created 2 years ago
- Comments:6 (4 by maintainers)
Top GitHub Comments
Latest builds are available here from https://github.com/hotwired/dev-builds/releases, so I think you could try:
I tend to agree. The same-page anchor system does use a
Visit
to do it’s thing, but the fired events do seem weird:turbo:click
turbo:before-visit
turbo:visit
turbo:before-cache
This could lead to some odd situations, particularly if people are tearing down JavaScript behaviour on
turbo:before-cache
I think same-page visits should be “silent” i.e. not fire
turbo:before-visit
,turbo:visit
, orturbo:before-cache
. This would also echo the behaviour that the native adapters take.