2

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

quetzalfir
  • 528
  • 7
  • 22

2 Answers2

3

One 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.

aidan
  • 1,627
  • 17
  • 27
0

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>
bilogic
  • 449
  • 3
  • 18