Controller not being initialized

I’m attempting to add Stimulus to a Rails 5.0.6 app that doesn’t use the asset pipeline. I am using Webpacker and Turbolinks along with Jammit to manage the assets.

I have added a controller and am trying to use it on a form, but the controller doesn’t ever seem to initialize.

I have this in my application.js file:

/* eslint no-console:0 */ import Turbolinks from 'turbolinks' import { Application } from "stimulus" import { definitionsFromContext } from "stimulus/webpack-helpers"

const application = Application.start()
const context = require.context("…/controllers", true, /.js$/)
application.load(definitionsFromContext(context))

// trying to fix the jQuery datepicker for Turbolinks
var element, i, len, ref;

document.addEventListener(“turbolinks:before-cache”, function() {
return $.datepicker.dpDiv.remove();
});

ref = document.querySelectorAll(“input.hasDatepicker”);
for (i = 0, len = ref.length; i < len; i++) {
element = ref[i];
$(element).datepicker(“destroy”);
}

document.addEventListener(“turbolinks:before-render”, function(event) {
return $.datepicker.dpDiv.appendTo(event.data.newBody);
});

Turbolinks.start()

require.context(’…/stylesheets/’, true, /^./[^_].*.(css|scss|sass)$/i)
require.context(’…/images/’, true, /.(gif|jpg|png|svg)$/i)

My app/javascript folder looks like:

`
├── controllers
│ └── bulletin_preview_controller.js

├── packs
│ ├── application.js

│ └── vendor.js
`

My question is how do I troubleshoot something like this?

Is your associated element correctly annotated with data-controller="bulletin-preview"?

You can inspect the controllers being loaded by logging them:

const context = require.context("../controllers", true, /.js$/)
console.log("controller definitions:", definitionsFromContext(context))
1 Like

I had underscores in the controller name instead of a dash. It is working now, thanks!

1 Like