-
-
Save vinnycrazzy/377f3e2f6355d1108b5ceab4b0baf0e8 to your computer and use it in GitHub Desktop.
Stimulus controller to alias other Stimulus controllers
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 { Controller } from "stimulus"; | |
export default class extends Controller { | |
initialize() { | |
this.registerAliasedControllers() | |
} | |
registerAliasedControllers() { | |
for (let [alias, original] of this.controllerIdentifiersByAlias) { | |
if (!this.moduleForIdentifier(alias)) { | |
this.application.register(alias, this.constructorForIdentifier(original)) | |
} | |
} | |
} | |
constructorForIdentifier(identifier) { | |
return this.moduleForIdentifier(identifier).definition.controllerConstructor; | |
} | |
moduleForIdentifier(identifier) { | |
return this.application.router.modulesByIdentifier.get(identifier) | |
} | |
get aliasDescriptors() { | |
return this.element.dataset.alias.split(/\s/); | |
} | |
get controllerIdentifiersByAlias() { | |
return new Map(this.aliasDescriptors.map(descriptor => descriptor.split(/->/))) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment