I have been using stimulus for my latest project, and I like how I can factor and modularize the code into small reusable parts.
However, there are times when generating a new controller and putting it as an element attribute is a bit cumbersome just to give it a specific functionality.
I don't know if it is possible to create a generic controller and pass it a function or callback to execute. So I can still maintain a reduced and clean code
I have been using stimulus for my latest project, and I like how I can factor and modularize the code into small reusable parts.
However, there are times when generating a new controller and putting it as an element attribute is a bit cumbersome just to give it a specific functionality.
I don't know if it is possible to create a generic controller and pass it a function or callback to execute. So I can still maintain a reduced and clean code
Share Improve this question asked May 11, 2021 at 1:21 quetzalfirquetzalfir 5688 silver badges23 bronze badges2 Answers
Reset to default 4One of the reasons Stimulus is great is that it's more or less just Javascript. Thus, you can have a method on your generic Stimulus controller that looks roughly like this:
execute() {
let fname = this.element.getAttribute("data-method")
// put this in a file somewhere else
let myFunctionMap = {
"scroll": () => {
// just a plain fn
},
"otherThing": () => {}
}
return myFunctionMap[fname]()
}
This would allow you to have a button in HTML like this:
<button
class="button button-primary"
data-action="generic#execute"
data-method="scroll">
Do the thing
</button>
Not exactly as simple as plain JS, but pretty close.
Yes there is.
// onconnect_controller.js
export default class extends Controller {
static values = {
callback: String,
};
connect() {
window[this.callbackValue]();
}
}
<div data-controller="onconnect" data-onconnect-callback-value="executeMe"></div>
<script>
function executeMe() {
console.log("I was executed");
}
</script>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745065178a4609211.html
评论列表(0条)