Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created March 2, 2023 13:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bennadel/f408cb60ba8d6f038bb6182c986c3563 to your computer and use it in GitHub Desktop.
Save bennadel/f408cb60ba8d6f038bb6182c986c3563 to your computer and use it in GitHub Desktop.
Dynamically Adding Stimulus Controllers To Static Content Using Hotwire And Lucee CFML
<cfmodule template="./tags/page.cfm">
<cfoutput>
<h2>
Welcome to My Site
</h2>
<div id="dyno">
This is static content.
</div>
<p>
<a href="javascript:( dyno.dataset.controller = 'dynamic-controller' );void(0);">
Attach Controller
</a>
</p>
</cfoutput>
</cfmodule>
// Import core modules.
import { Application } from "@hotwired/stimulus";
import { Controller } from "@hotwired/stimulus";
import * as Turbo from "@hotwired/turbo";
// ----------------------------------------------------------------------------------- //
// ----------------------------------------------------------------------------------- //
class DynamicController extends Controller {
/**
* I get called whenever this controller instance is bound to a host element.
*/
connect() {
console.group( "Dynamic Controller" );
console.log( "Connected!" );
console.log( this.element );
console.groupEnd();
this.element.classList.add( "enhanced" );
}
}
// ----------------------------------------------------------------------------------- //
// ----------------------------------------------------------------------------------- //
window.Stimulus = Application.start();
// When not using the Ruby On Rails asset pipeline / build system, Stimulus doesn't know
// how to map controller classes to data-controller attributes. As such, we have to
// explicitly register the Controllers on Stimulus startup.
Stimulus.register( "dynamic-controller", DynamicController );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment