
Stimulus Controllers That Stay Small
We are lazy sometimes with disconnect, so we decided to punish ourselves and wrote three tiny Stimulus controllers with zero cleanup, one with timer, one dropdown, one which glues its own element inside like date pickers like to do, and clicked between two Turbo pages.
After one trip away and back button there were 2 timers running instead of 1, the dropdown came back open, and our appended element was there twice. After four more trips we had 6 timers and 6 copies of the element, the timer callback fired 60 times per second where it should be 10, and nothing in console was complaining, the page just becomes slower and stranger.
Why it happens we understood so: Turbo does not reload anything, interval from connect keeps ticking although its element is in the garbage, and when you leave the page Turbo makes a photo of it, with open menu, with our extra element, shows you the photo on return, and connect runs again on top, hello doubles.
export default class extends Controller {
static values = { interval: { type: Number, default: 5000 } }
connect() {
this.timer = setInterval(() => this.refresh(), this.intervalValue)
}
disconnect() {
clearInterval(this.timer)
}
refresh() {
this.element.reload()
}
}
So we wrote the boring lines, clearInterval and element removal in disconnect, menu closing on turbo:before-cache, walked the same walk, and got one timer, one element, closed menu, 10 ticks in second. In our review now we ask for every thing born in connect, where does it die?
connect() {
this.reset = () => this.close()
document.addEventListener("turbo:before-cache", this.reset)
}
disconnect() {
document.removeEventListener("turbo:before-cache", this.reset)
}
<div data-controller="menu" data-action="keydown.esc@window->menu#close">
See also: The Hotwire overview.