避免在meteor模板帮助程序中重复查询
我开始在一个项目中使用meteor,从angular+php中有几个概念对我来说非常困难 我试图处理两个助手,用于根据存储在会话变量上的日期范围在表中显示记录列表。我的模板是这样的,我使用一个名为noRecords的助手和另一个名为records的助手,records存储实际的文档集,在noRecords中,我尝试将记录文档集是否为空存储为布尔值避免在meteor模板帮助程序中重复查询,meteor,Meteor,我开始在一个项目中使用meteor,从angular+php中有几个概念对我来说非常困难 我试图处理两个助手,用于根据存储在会话变量上的日期范围在表中显示记录列表。我的模板是这样的,我使用一个名为noRecords的助手和另一个名为records的助手,records存储实际的文档集,在noRecords中,我尝试将记录文档集是否为空存储为布尔值 div(class='col-md-8 col-md-offset-2') if noRecords
div(class='col-md-8 col-md-offset-2')
if noRecords
p There are no records for the selected date
else
table(class='table table-bordered')
thead
tr
td Id
td Name
tbody
each records
+record
不幸的是,我无法在不重复查询的情况下同时设置记录和noRecords,在我的javascript代码中,这些帮助程序的定义如下:
records : function(){
var startDate = Session.get('searchDate').setHours(0,0,0,0);
var endDate = Session.get('searchDate').setHours(23,59,59,999);
var matches = Records.find(
{date : {
$gte : new Date(startDate),
$lte : new Date(endDate)
}
});
return records;
},
noRecords : function(){
var startDate = Session.get('searchDate').setHours(0,0,0,0);
var endDate = Session.get('searchDate').setHours(23,59,59,999);
var matches = Records.find(
{date : {
$gte : new Date(startDate),
$lte : new Date(endDate)
}
});
return records.count() === 0;
}
日期会话变量由事件设置
我想一定有更好的方法来实现这一点,而不是执行两次查询,我尝试过使用反应变量,但没有成功,因为我无法在执行minimongo查询时更新反应变量
有没有办法在不运行两个查询的情况下实现这一点?如果在多个帮助程序中重复相同的逻辑,一个解决方案是将它们简化为单个帮助程序并从中返回一个对象,例如:
records : function(){
var startDate = Session.get('searchDate').setHours(0,0,0,0);
var endDate = Session.get('searchDate').setHours(23,59,59,999);
var cursor = Records.find(
{date : {
$gte : new Date(startDate),
$lte : new Date(endDate)
}
});
return {
cursor: cursor,
empty: cursor.count() === 0,
one: cursor.count() === 1
}
}
在模板中:
if records.one
p Found One!
这是一个愚蠢的例子,但它可以被更广泛地使用
请注意,在您的示例中,您实际上不需要noRecords
帮助程序,因为您的模板可以检查空光标:
each records
p date
else
p No records!
如果您使用的是Blaze,则只能像这样使用
记录
帮助程序使用{{{{each records}}}}…{{else}}…{{/each}}
<template name="myTemplate">
<div class='col-md-8 col-md-offset-2'>
{{#each records}}{{> showRecord}}
{{else}}<p>There are no records for the selected date</p>
{{/each}}
</div>
</template>
呃,
函数getValues(){return/*任何您想要的值数组*/}
?要求“最干净的方式”是离题的,因为它是基于意见的(您可能想重新表述),但减少代码重复的通常解决方案是将其包装在函数中。感谢您的回答,我编辑了我的问题,但我更担心的是执行两次查询,而不是编写两次查询,将其包装在函数中仍然会使其执行两次。如果不是很清楚,很抱歉。您可以使用和
来获取记录,如果它们的计数为正,请迭代。否则,显示no records
段落。我已经回答了一个类似的(尽管更简单)问题。最后一个代码示例将在有记录的情况下调用records
helper两次。你可能有别的意思。啊,没错,你们甚至不需要彼此,你们只需要彼此。据我所知,#with
不会迭代其输入,我将进行编辑以改进答案(两者都会起作用)。此外,您的第二个代码示例有几个问题。你能指出一些显示#with
执行迭代的东西吗?那是一个错误,我的意思是#每个
<template name="myTemplate">
<div class='col-md-8 col-md-offset-2'>
{{#if records}}
<table class='table table-bordered'>
<thead>
<tr>
<td>Id</td>
<td>Name</td>
</tr>
</thead>
<tbody>
{{#each}}{{> showRecord}}{{/each}}
</tbody>
</table>
{{else}}<p>There are no records for the selected date</p>
{{/with}}
</div>
</template>