【发布时间】:2017-12-18 08:50:30
【问题描述】:
我正在构建一个基于 jquery 和 firestore 的聊天,我设法检索按日期排序的 onSnapshot 消息,但现在我尝试按天添加日期分隔符,因此当用户打开聊天时,他会找到一个分隔符对于每一天,每个分隔线下的消息都发生在这一天。
这是我的代码:
firestore.collection("chat").orderBy("date","desc").limit(10).onSnapshot(function(snapshot) {
$(".messages").html('');
var curUser = '';
var curDate = '';
var curDay = '';
snapshot.forEach(function(doc) {
console.log("djsidjsdoisjdis");
$(".chat-content").animate({ scrollTop: $('.chat-content').prop("scrollHeight")}, 100);
if(curDate!== doc.data().date.toLocaleDateString()){
curDate=doc.data().date.toLocaleDateString();
$(".messages").append('<h1>'+doc.data().date.toLocaleDateString()+'</h1>');
}
if(doc.data().user_name != username){
// My message
if(doc.data().user_name !== curUser) {
// SHOW USER NAME
curUser = doc.data().user_name;
$(".messages").append('<ul class="message message-received message-appear-from-bottom message-appeared message-first message-last message-with-tail"><li class="message-name">'+doc.data().user_name+'</li><li id="message-date" class="hide">'+doc.data().date+'</li><li class="message-text">'+doc.data().message+'</li></ul>');
} else {
// SHOW MESSAGE WITHOUT USERNAME
$(".messages").append('<ul class="message message-received message-appear-from-bottom message-appeared message-first message-last message-with-tail"><li id="message-date" class="hide">'+doc.data().date+'</li><li class="message-text">'+doc.data().message+'</li></ul>');
}
} else {
// other users messages
if(doc.data().user_name !== curUser) {
// Show messsgae with user name:
curUser = doc.data().user_name;
$(".messages").append('<ul class="message message-sent message-first message-last message-with-tail message-appear-from-bottom message-appeared"><li id="message-date" class="hide">'+doc.data().date+'</li><li class="message-name">'+doc.data().user_name+'</li><li class="message-text">'+doc.data().message+'</li></ul>');
} else {
// Show message without user name:
$(".messages").append('<ul class="message message-sent message-first message-last message-with-tail message-appear-from-bottom message-appeared"><li id="message-date" class="hide">'+doc.data().date+'</li><li class="message-text">'+doc.data().message+'</li></ul>');
}
}
});
var list = $('.messages');
var listItems = list.children('ul.message');
list.append(listItems.get().reverse());
});
这是我得到的屏幕截图,我在彼此之后得到了日期分隔符,而不是分隔消息。 chat
【问题讨论】:
-
你能分享你的 json 的摘录吗?在你的情况下
snapshot -
@KresimirPendic 我没有在这个函数中包含 json,用户名现在被定义为静态变量。因为我只想在分隔日期下对来自 firestore 的消息进行排序
标签: javascript jquery firebase firebase-realtime-database