重用 blaze 模板,如何访问其他模板的辅助函数?

Reusing a blaze template, how do I access other template's helper functions?

我正在尝试设置 MDC 对话框警告。我没有将它复制粘贴到每个需要它的视图中,而是将对话框包装在它自己的模板中。该模板似乎有效,对话框打开并正常运行,但是,我无法为其设置有效的辅助函数。我尝试使用父模板的辅助函数,甚至创建新模板它自己的 js 文件。这些解决方案都没有正确获取数据。

<template name="transactionAlert">
...
<div class="mdc-dialog__content" ><p>Are you sure you wish to continue with this transaction? It could cost up to: <b class="warning-value">${{maxCost}} USD</b></p>
...
</template>
<template name="transactionCreate">
...
    {{>transactionAlert}}
</template>
Template.transactionAlert.onCreated(function transactionAlertOnCreated() {
    console.log('test')
})

Template.transactionAlert.helpers({
    maxCost(){
        console.log('test 2')
        const instance = Template.instance()
        return instance.maxTxCost.get().toString().slice(0,5);
    }
})

I tried using the helper function of the parent template

此类问题通常是由设计问题引起的,而不是遗漏或错误的实施。如果我们认为您的 transactionAlert 是无状态的(它不包含任何相关的视图逻辑或内部状态管理),那么它也不应该访问超出其范围的属性或助手。

否则,您将创建一个如此紧密的耦合,以至于它会在两年左右的时间内重新出现在您面前(当重构 session 调用时)。

相比之下,parent 模板的职责是

  • 管理数据状态(订阅、数据 post-processing 等)
  • 检查条件,transactionAlert是否应该出现或消失
  • 将适当的参数传递给 transactionAlert 模板

因此,您可以将交易警报设计为参数化模板:

<template name="transactionAlert">
...
<div class="mdc-dialog__content" ><p>Are you sure you wish to continue with this transaction? It could cost up to: <b class="warning-value">${{maxCost}} USD</b></p>
...
</template> 

如您所见,它看起来完全一样。不同之处在于,您删除了 Template.transactionAlert.helpers 并导致模板查找正在传递给模板的 maxCost

现在,在您的 parent 模板中,一旦警报条件适用,您将把数据传递给 transactionalert

<template name="transactionCreate">
  {{#if showAlert}}
    {{>transactionAlert maxCost=getMaxCost}}
  {{/if}}
</template>

帮手现在所在的位置:

Template.transactionCreate.helpers({
    showAlert () {
      return Template.instance().showAlert.get()
    },
    getMaxCost(){
      const instance = Template.instance()
      return instance.maxTxCost.get().toString().slice(0,5);
    }
})

因为您需要对 show/hide 警报做出反应,您将使用模板的内部跟踪器:

Template.transactionCreate.onCreated(function () {
  const instance = this
  instance.showAlert = new ReactiveVar(false)
  instance.autorun(() => {
    const maxCost = instance.maxTxCost.get()
    if (/* max cost exceeds limit */) {
      instance.showAlert.set(true)
    } else {
      instance.showAlert.set(false)
    } 
  })
})

编辑:关于反应性的附加信息

反应性是 Meteor 客户端生态系统的一个主要概念。它基于 Tracker package, which is linked to any Template instance. The guide to the reactive data stores explains the concept a bit further: https://guide.meteor.com/data-loading.html#stores