我有一个应用程序,用户可以在不同的日期时间签入。然后,我的目标是显示谁在不同的日期在那里。
像这样的东西:
11/05:Mat,Lisa,Andrew
14/05:丽莎
ETC。
我看了$ groupby聚合,但是对于我的简单用法而言,它看起来确实很沉重。我也可以在db.find()。fetch()上循环,但我感觉自己会失去反应性。
我设法使其与一个简单的模板助手一起工作:
resultDate = null;
Template.result.helpers({
date: function(){
var date = moment(this.datetime).endOf("day").fromNow();
if(date == resultDate)
return false;
resultDate = date;
return date;
}
}
但是,正如您所看到的,这并不是真正的经典方法,例如,如果我需要两次致电{{date}},一切都会崩溃。
我找了好几个小时的解决方案,却一无所获。任何的想法?
谢谢!
这是一个如何在您的收藏夹中进行此客户端操作而又不失去反应性的示例。
关键问题是将反应性数据源(集合)转换为对象数组,该对象数组将以签入人员的姓名反映所需的日期输出。此数组类似于:
[
{date: '2015-05-11', names: ['Mat', 'Lisa', 'Andrew']},
{date: '2015-05-14', names: ['Lisa']},
]
我假设您的集合称为Checkin,每个文档中都有2个字段,date
并且name
。
您的集合是反应性数据源。您可以通过接收有关集合更改的通知observeChanges
。通过触发添加,更改和删除的事件,您可以每天通过检入来重建阵列。所有事件将调用rebuildCheckinPerDay
以构建实际数组。然后,checkinPerDateVar
每次重建阵列时,将其保存在ReactiveVar中。并且由于ReactiveVar也是反应式数据源,因此checkinPerDate
每次更改ReactVar时,模板帮助程序都会重新运行。
构建数组是由几个underscorejs函数完成的。首先,将集合按日期排序并提取到数组中,然后按日期分组(时间已被删除.endOf('day')
),然后映射到最终结构。由于_.groupBy
返回的项目为{id,name,date},因此必须_.pluck
提取名称。
为了转换日期和方便的模板助手来格式化日期,我使用了momentjs。要实际运行此示例,您必须包含软件包momentjs:moment
和reactive-var
。在示例中,将显示完整日期。但是,moment(this.datetime).endOf("day").fromNow()
如果愿意,您可以轻松地将其转换为。
完整示例:
check-in.html。
<template name="checkinPerDate">
{{#each checkinPerDate}}
<div>
{{formatDate date}} - {{names}}
</div>
{{/each}}
</template>
check-in.js。
Template.registerHelper('formatDate', function(date) {
return moment(date).format('DD-MM-YYYY');
});
// Reactive variable to hold the array with names per check-in day
var checkinPerDateVar = new ReactiveVar([]);
// Build the array with check-ins per day that mirror the final view in the template
var rebuildCheckinPerDay = function() {
var checkinPerDateArray = _.map(
_.groupBy(Checkin.find({}, {sort: {date : 1}}).fetch(), function(item) {
return moment(item.date).endOf('day');
}), function(dateItem, date) {
return {date: date, names: _.pluck(dateItem, 'name')};
});
checkinPerDateVar.set(checkinPerDateArray);
}
Template.checkinPerDate.onCreated(function() {
this.subscribe('checkin', function() {
var cursor = Checkin.find();
var handle = cursor.observeChanges({
added: function (id, checkin) {
console.log('added ', id, JSON.stringify(checkin));
rebuildCheckinPerDay();
},
changed: function (id, checkin) {
console.log('changed ', id, JSON.stringify(checkin));
rebuildCheckinPerDay();
},
removed: function (id) {
console.log('removed ', id);
rebuildCheckinPerDay();
}
});
});
});
Template.checkinPerDate.helpers({
// This helper function is reactive because of the use of reactive variable checkinPerDateVar.
// It gets rerun each time the variable was changed
checkinPerDate: function () {
var checkinPerDateArray = checkinPerDateVar.get();
return checkinPerDateArray;
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句