我正在尝试设置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);
}
})
我尝试使用父模板的辅助函数
这些问题通常是由设计问题引起的,而不是遗漏或错误的实施。如果我们认为你的transactionAlert
是无状态的(它不包含任何相关的视图逻辑或内部状态管理)那么它既不应该访问属性也不应该超出它的范围。
否则你会创建这样一个紧密耦合,它会在两年左右的时间内重新出现(当重构会话正在调用时)。
相比之下,父模板的职责是
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
。
现在,在您的父模板中,一旦警报条件适用,您就会将数据传递给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);
}
})
因为您需要反应来显示/隐藏警报,您将使用模板的内部跟踪器:
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包,它与任何Template
实例相关联。反应数据存储指南进一步解释了这个概念:https://guide.meteor.com/data-loading.html#stores