最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - pass a function to stimulus - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 4

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.

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>
发布评论

评论列表(0)

  1. 暂无评论