【问题标题】:pass a function to stimulus将函数传递给刺激
【发布时间】:2021-08-01 09:17:15
【问题描述】:

我一直在为我的最新项目使用刺激,我喜欢如何将代码分解和模块化成小的可重用部分。

但是,有时生成新的控制器并将其作为元素属性只是为了赋予它特定的功能有点麻烦。

我不知道是否可以创建一个通用控制器并传递一个函数或回调来执行。所以我仍然可以保持精简和干净的代码

【问题讨论】:

    标签: javascript callback stimulusjs hotwire-rails


    【解决方案1】:

    Stimulus 很棒的原因之一是它或多或少只是 Javascript。因此,您可以在通用 Stimulus 控制器上拥有一个大致如下所示的方法:

      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]()
      }
    

    这将允许您在 HTML 中拥有这样的按钮:

          <button
            class="button button-primary"
            data-action="generic#execute"
            data-method="scroll">
            Do the thing
          </button>
    
    

    不像普通的 JS 那样简单,但非常接近。

    【讨论】:

      猜你喜欢
      • 2023-03-31
      • 2020-07-28
      • 2013-01-27
      • 2014-09-10
      • 2013-01-10
      • 2010-11-01
      • 2016-04-27
      • 2014-04-10
      • 2012-05-07
      相关资源
      最近更新 更多