[英]Switch in Meteor template helper
我有一个带有表格的模板,该表格是通过遍历一系列用户选择的公司而创建的,这些公司通过股票代码存储在称为selections
的文档属性中。 我会根据不同的用户选择(称为metric
显示与每个公司相关的不同值。
我在编写需要根据用户选择更改值的if / else语句时遇到麻烦。 使用下面的代码, headingNum
和headingDen
正确显示。 与单个选择相关联的companyName
也是如此。 如果我用this.reported.capTable.enterpriseValue
替换valuationNum
, this.reported.capTable.enterpriseValue
显示正确的值。 但是我无法在使用帮助程序时显示它。
<template name="Table">
<div>
<table>
<thead>
<tr>
<th>Company</th>
<th>{{headingNum}}</th>
<th>{{headingDen}}</th>
</tr>
</thead>
<tbody>
{{#each selections}}
<tr>
<td>{{companyName}}</td>
<td>${{valuationNum}}</td>
<td>${{valuationDen}}</td>
</tr>
{{/each}}
</tbody>
</table>
</div>
</template>
JS文件
var metric = this.metric;
var period = this.period;
Template. Table.helpers({
selections: function () {
var selected = this.selections;
return Companies.find({ticker: {$in: selected}})
},
headingNum: function () {
switch (metric) {
case "A":
return "EV";
break;
case "B":
return "Price";
break;
default:
return "EV"
}
},
valuationNum: function() {
switch (metric) {
case "A":
return this.reported.capTable.enterpriseValue;
break;
case "B":
return this.reported.capTable.lastClose;
break;
default:
return ""
}
}
});
我尝试将{{#each}} {{each}}块分解为一个新模板,以查看它是否对数据上下文有帮助,但没有运气(它弄乱了表)。
我写的这些助手正确吗? 我还在JS文件中收到一条错误消息,说reported
是一个未解决的变量,即使那是正确的路径。
谢谢。
编辑:
此帮助程序有效,不确定另一个为什么不这样做:
headingNum: function () {
var metric = this.metric;
switch (metric) {
case "EV/EBITDA":
return "EV";
break;
case "Price/Earnings":
return "Price";
break;
default:
return ""
}
}
流星的模板建立在blaze之上,后者根据设计具有反应性。 这意味着仅当数据依赖项值更改时,模板才会重新呈现。 在此示例中,仅当您修改Companies
。 但是,当您修改metric
的值时,模板将不会重新呈现,这就是为什么您看不到预期的更改的原因。
实现目标的反应方式实际上是在模板内部放置度量标准切换逻辑:
{{#each selections}}
<tr>
<td>{{companyName}}</td>
{{#if metricA}}
<td>${{reported.capTable.enterpriseValue}}</td>
{{else}}
<td>${{reported.capTable.lastClose}}</td>
{{/if}}
<td>${{valuationDen}}</td>
</tr>
{{/each}}
在您的JS中:
Template. Table.helpers({
metricA: function() {
return this.metric == 'A';
}
})
只需快速浏览一下代码,就可以了解几件事。
您已在窗口范围而非模板范围设置了度量和期间变量。 这就是为什么您无法访问助手中的指标变量的原因。 要解决此问题,只需从最初创建metric变量的位置删除var。 但是,这不是管理范围和变量管理的好方法。
我想说,要使其真正有效,您需要一个帮助器和事件处理程序来以反应方式跟踪度量的获取和设置(reactive-var软件包对此有所帮助)
设置指标反应变量
Template.Table.created = function() {
this.metric = new ReactiveVar();
}
获取指标
Template.Table.helpers({
getMetric: function() {
return this.metric.get();
}
})
设置指标
Template.Table.events({
'click .setMetric': function(event, template) {
event.preventDefault();
var metric = $(event.target).data('metric');
if(metric) template.data.metric.set(metric);
}
});
然后使用这些作为策略,您可以简单地为标题和值提供帮助-确定按需度量并加以限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.