Skip to main content

BaseController

Purpose

Provide common utilities and base functionality for all Stimulus controllers that extend this controller.

Properties

This controller provides the following properties to controllers that extend it.

NamePurposeReturn Value
elFor Typescript projects, provides a wrapper around this.element typecast to HTMLElement so that type-hinting correctly works for all DOM APIsThe controller root element, as an HTMLElement
isTurboPreviewWhether or not the document is currently displaying a preview from the Hotwire/Turbo cache https://turbo.hotwire.dev/handbook/building#detecting-when-a-preview-is-visible. Also works with legacy Turbolinksboolean
isTurbolinksPreviewAlias for isTurboPreview, both methods work for both Turbolinks and Hotwireboolean
csrfTokenThe current Rails CSRF token, taken from the <meta> tag Rails inserts into the document head, if present.string or null

Methods

This controller provides the following methods to controllers that extend it.

NameParametersPurposeDefault
dispatchEventDispatch a custom event
elementThe element to dispatch the event on
eventNameThe fully qualified name of the event. Usually follows the format controller-identifier:event
options (Optional)The options to initialize the event with. See the options eventInit accepts: https://developer.mozilla.org/en-US/docs/Web/API/Event/Event{ bubbles: true, cancellable: true, details: { element: this.element } }
NameParametersPurposeReturn value
metaValueFetch a value from a <meta> tag in the <head> of the document.string or null
nameThe name attribute of the meta tag to fetch the value of
NameParametersPurposeReturn value
eventNameConstruct an colon separated event name using the controllers identifier .i.e in FooController calling eventName("loaded") would result in foo:loaded.string
eventNameThe name of the event to append to the controllers identifier to create a fully namespaced event

Side Effects / Inherited Behaviour

If debug mode is enabled, any controller that extends BaseController controller will automatically log calls to any actions or methods, and events dispatched with the dispatchEvent method provided by stimulus-library.

If there are any getters, setters, methods or properties that should not be logged, you should name them with an underscore prefix i.e. _foo() {}, or _bar = "baz" to indicate that they are private methods.

How to Use

import {BaseController} from "stimulus-library";

export default class FooController extends BaseController {
// ...

foo() {
this.dispatchEvent(this.el, "foo:something-happened", { bubbles: true, cancellable: true, detail: { element: this.el, data: 'thing' } } ) // dispatches a custom event named `foo:something-happened`
// or
this.dispatchEvent(this.el, this.eventName("something-happened"), { bubbles: true, cancellable: true, detail: { element: this.el, data: 'thing' } } ) // also dispatches `foo:something-happened`
}

}