【问题标题】:Firebase child_added event listener returning duplicate dataFirebase child_added 事件侦听器返回重复数据
【发布时间】:2016-06-07 00:16:51
【问题描述】:

我正在使用 Firebase child_added 来监视添加到我的数据库中的新条目。

它似乎工作了一段时间,但是当连接空闲时我注意到了一些问题。如果我在 Firebase 返回重复项时让我的应用程序长时间打开。我认为这可能归结为连接被丢弃然后建立。

这是我的代码。

getVoicemailList: function() {
    var self = this;
    var userId = firebase.auth().currentUser.uid;       
    firebase.database().ref('voicemails/' + userId).on('child_added', function(snapshot) {
         var voicemail = snapshot.val();
         self.addToCollection(voicemail.callerID, voicemail.timeReceived, voicemail.transcription, voicemail.audioURL);
    });
},

addToCollection: function(callerID, timeReceived, transcription, audioURL) {
    console.log(callerID)
    var collectionList = $('.collapsible').length;

    if(!collectionList) {
        $('#main-content').append('<ul class="collapsible" data-collapsible="accordion"></ul>')
    }

        var output = '<li>';
        output +=  '<div class="collapsible-header"><i class="material-icons">filter_drama</i>'+callerID+'</div>';      
        output += '<div class="collapsible-body">';
        output += '<p><audio id="source" controls>';            
        output += '<source src="'+audioURL+'" type="audio/mpeg">';
        output += '</audio></p>';
        output += '<p>'+timeReceived+'</p>';
        output += '<p>'+transcription+'</p>';   
        output += '</div>';     
        output += '</li>';
        $('.collapsible').append(output);
        $('.collapsible').collapsible();
},

【问题讨论】:

  • 绝对不应该这样。你确定 getVoicemailList 只被调用一次吗? Firebase SDK 对于不引发重复事件非常小心。您能否指定您正在使用的 Firebase SDK 的版本并提供 MCVE (stackoverflow.com/help/mcve)?

标签: javascript jquery firebase firebase-realtime-database


【解决方案1】:

如果我正确理解了您的问题,那么这就是我遇到过几次的问题。我相信诀窍是 .empty() 来自 .on 调用中的现有数据。

例如,在我的网站上,我们有用户可以添加的目标。当他们添加一个新的Goal时,.on 调用会在他们列表的底部添加一个新的Goal

我遇到了一个问题,即删除 目标 会复制 UI 数据。

为了解决这个问题,我将$(#goals").empty(); 移到了.on 调用中。

  firebase.database().ref('users/' + user).on('value', function(snapshot) {
    $("#goals").empty(); // This removes all all previously added goals

    snapshot.forEach(function(data) {
        var id = data.key;
        var desc = data.val().desc;
        var url = data.val().url || "https://unsplash.it/400?image=" + getRandomNumber();
        displayGoal(id,desc,url);
    });
// If you need to append anything after all the data has been added you can do it here. e.g. $("#goals").append("</div>");
  });

我怀疑这样做会强制重新加载所有相关的 UI 项,但事实并非如此。如果我添加一个 Goal,它只会在列表底部弹出,如果我删除一个 Goal,UI 只会删除目标,而无需重新加载或复制。

因此,在您的情况下,您可以在.on 调用之后和var voicemail = snapshot.val(); 之前添加$('.collapsible').empty();

注意:以前我会在.on 调用之前调用$("#goals").empty()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多