Skip to main content Link Menu Expand (external link) Document Search Copy Copied

Application Controller

by @julianrubisch julianrubisch

Good

// application_controller.js
import { Controller } from "@hotwired/stimulus";

export default class extends Controller {
  sayHi () {
    console.log("Hello from the Application controller.");
  }
}
// custom_controller.js
import ApplicationController from "./application_controller";

export default class extends ApplicationController {
  sayHi () {
    super.sayHi();
    console.log("Hello from a Custom controller");
  }
}

Rationale

You can make use of JavaScript’s class inheritance to set up an “Application Controller” that will serve as the foundation for all of your controllers to build upon. This not only reduces boilerplate, but it’s also a convenient way to set up lifecycle callback methods for your entire application.

Counterindications

Inheritance isn’t always the answer to share behavior. Before bloating your ApplicationController, ask yourself if what you’re implementing isn’t a specialization but a role (has a “acts as a” relationship to your class - use mixins) or a attributes or property (has a “has a” relationship to your class - use composition).

References

Codesandbox Example