Created
March 2, 2023 13:26
-
-
Save bennadel/f408cb60ba8d6f038bb6182c986c3563 to your computer and use it in GitHub Desktop.
Dynamically Adding Stimulus Controllers To Static Content Using Hotwire And Lucee CFML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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