Stimulus Discourse

Component is mounting twice on turbolinks navigation


#1

I understand it’s expected for a component to mount twice when turbolinks navigates due to it’s preview feature, however they’re not disconnecting. This compounds on multiple navigations, so I end up having an exponential growth of duplicated controllers.

The controller is mounted like so:

    <div data-controller="nav" data-nav-open="false">
      <%= render "shared/nav_drawer" %>
      <div class="mdc-drawer-app-content">
        <%= render "shared/navbar" %>
      </div>
    </div>

The controller itself looks like this:

import { Controller } from 'stimulus';
import { drawer } from 'material-components-web/index';

export default class extends Controller {
    static targets = [ 'drawer' ];
    readonly drawerTarget: HTMLElement;
    drawer: drawer.MDCDrawer;

    initialize() {

    }

    connect() {
        console.log("Connected");
        this.drawer = new drawer.MDCDrawer(this.drawerTarget);
    }

    disconnect() {
        console.log("Disconnected");
    }

    get open() {
        return this.data.get('open') === "true";
    }

    set open(state) {
        this.drawer.open = state;
        this.data.set('open', state.toString());
    }

    toggleDrawer() {
        this.open = !this.open;
    }
}

#2

Bah.

Immediately after posting this, I realized I had the javascript_pack_tag at the bottom of the html body. This was causing the entire application to be loaded again, causing my issue.