能否从模板向小部件操作注入参数?

继续讨论来自 Discourse 主题开发者指南

大家好,

我在想是否可以从模板向操作注入参数,但在 @Johani 的指南中未能找到肯定或否定的答案。我的目标是让模板生成多个组件,而每个组件的操作能够知晓 {{#each}} 循环中的参数。

例如,在选择分类通知多选按钮后:

<script type="text/x-handlebars" data-template-name="components/some_component">
{{#each categories as |c|}}
    {{category-notifications-button
        value=c.notification_level
        category=c
        onChange=(action "changeCategoryNotificationLevel" ***以某种方式注入 c 作为参数***)
    }}
{{/each}}
</script>
<script type="text/discourse-plugin" version="0.8">
  api.modifyClass("controller:some_component", {
    actions: {
      changeCategoryNotificationLevel(selected_value, ***c 作为参数***) {
        c_as_a_parameter.setNotification(notificationLevel);
      }
    }
  }
});
</script>

changeCategoryNotificationLevel 内部,是否有办法知道当前来自模板的是哪个分类?

如果不能,如果我的问题描述得足够清楚,是否有人能看到其他实现相同效果的方法?

提前感谢

1 个赞

我找不到关于这个通用问题的任何信息,但我可以通过以下方式解决我的问题:

{{#each categories as |c|}}
    {{category-notifications-button
        ...
        onChange=(action (mut c.notification_level))
    }}
{{/each}}

这意味着,我想用按钮返回的值来修改字段 c.notification_level

实际上,我的问题无法通过上述方式解决:

  • 是的,通知级别确实被修改了,但是…
  • 它并没有被保存。需要点击其他地方通过其他操作来保存。

通过在 GitHub 代码数据库中大量搜索随机关键词,我找到了一些类似这样的结构:
{{d-button action=(action "up" wc) ...}}

经过一些测试,我得出了以下结论:

  • 模板:
    {{d-button action=(action "操作名称" arg1 arg2) ...}}`
    
  • JS:
    api.modifyClass("component:some-component", {
        actions: {
            操作名称(arg1, arg2, argA, argB) {
                console.log(arg1);
                console.log(arg2);
                console.log(argA);
                console.log(argB);
            }
        }
    })
    

方法的第一个参数 arg1arg2 是由模板提供的。其余参数 argAargB 等可能由组件的特性决定(例如,category-notifications-button 会根据用户点击的设置返回一个整数)。

我完全不确定我所写的内容是否正确,但这或许能帮助那些和我提出同样问题的人。

1 个赞