Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass a function to stimulus

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

like image 512
quetzalfir Avatar asked Jun 06 '26 07:06

quetzalfir


2 Answers

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.

like image 90
aidan Avatar answered Jun 08 '26 20:06

aidan


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>
like image 34
bilogic Avatar answered Jun 08 '26 20:06

bilogic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!