Firebase child_added创建重复项 [英] Firebase child_added creates duplicates
问题描述
我正在使用Firebase开发HTML5移动消息传递应用程序.我遇到了无法解决的问题.该应用程序具有多个频道(聊天室).第一次将消息添加到某个频道时,它可以按预期工作,但是当我转到其他频道并向该频道发布新消息时,我返回到上一个频道并发布另一条消息,我得到了上次发布的副本信息.当我重新加载页面时,重复项消失了,但我不希望完全不显示重复项.下面是我的代码:
I am using Firebase to develop an HTML5 mobile messaging app. I encountered an issue that I am unable to resolve. The app has multiple channels (chat rooms). When a message is added for the first time to a channel it works as expected but when I go to a different channel and post an new message to that channel then I return to the previous channel and post another message I get duplicates of the last posted message. When I reload the page the duplicates are gone but I'd prefer not to have duplicates showing at all. Below is my code:
function loadChatMessages(channelID) {
$('#chatMessages').html('');
var msgObj = {};
var channelRef = globals.channelsBase + '/' + channelID + '/messages';
var channelMessages = new Firebase(channelRef);
channelMessages.on('child_added', function (snapshot) {
msgObj = snapshot.val();
var id = snapshot.name().toString();
var messageTime = application.Functions.renderTime(msgObj.messageTime);
var tails = '<div class="message-tails-wrap"><div class="message-tails"></div></div>';
var html = '<li class="chatEl ' + sentByClass + '" id="'+id+'">';
html += tails;
html += msgObj.message;
html += '<span class="sender"> ' + by + ' </span> <span class="tmp-recipient"> ' + msgObj.recipient + ' </span>';
html += '<span class="time-stamp msg-time" >';
html += messageTime;
html += '</span></li>';
$(html).appendTo('#chatMessages');
/// TODO: TEMP solution!
var prevID = 0;
$('#chatMessages li').each(function(n) {
var id = $(this).attr('id');
if(id == prevID){
// console.log(id + ' is a duplicate. Remove it');
this.remove(); // the necessary evil....
}
prevID = id;
});
});
}
推荐答案
听起来像您每次进入房间都运行 loadChatMessages()
,并且随着用户在房间中四处移动,您正在看到重复调用 on('child_added'
回调.
It sounds like you run loadChatMessages()
every time you enter a room, and as your users move around rooms, you're seeing duplicate calls to your on('child_added'
callback.
这是因为每次重新进入房间时,您都将添加一个新的回叫.要解决此问题,请在用户离开房间时进行一些清理.在该清理功能中,请确保使用 .off("child_added")
删除旧的侦听器.
This is because you're adding a new callback every time you re-enter a room. To resolve this, do some clean up when your users leave a room. In that clean up function, make sure you remove the old listener using .off("child_added")
.
这篇关于Firebase child_added创建重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!