Firebase网络应用聊天重复聊天输入

时间:2014-08-26 06:36:41

标签: jquery firebase

您好我是firebase的新手并且正在尝试开发一个聊天应用程序,一切看起来都可以处理聊天消息,只要用户切换到pm其他用户时它就会复制发件人面板上的数据。在他/她回到之前的用户之后,它也复制了该人的聊天...虽然它没有存储在firebase数据库上,这也很奇怪..重复从1开始然后在它之后如果用户增加再次切换到其他用户

以下是聊天应用程序的整个firebase代码,这是在线状态和聊天教程的组合我只是对它做了一个小修改,我不知道哪个脚本导致了这个重复

   // Reference for tbl message
  var messagesRef = new Firebase('https://url-for-tablemessage');


  // Reference for tbl userprofile
  var userListRef = new Firebase("https://url-for-userprofile");


  var myUser = userListRef.child(idf);
  // Get a reference to my own presence status.
  var connectedRef = new Firebase("https://url-for-userprofile//.info/connected");

 function getmsg(){
            // Loads Previous Message with the selected user/s.
     messageList.html("");
     messagesRef.limit(10).on('child_added', function (snapshot) {
           //GET DATA
           var data = snapshot.val(), username = data.name, message = data.text,
               sendr = data.sender, recievr = data.reciever, ui =  $('#chat-avatar').attr("data-ui"),
               style_c = "";

 if (username != nameField){ style_c = "message chat";}
             else{ style_c = "message user";  }

                    var messageElement = $('<div class="'+style_c+'"><div class="message-info">'+
             '<img width="40" height="40" src="temp/user/'+username+'.jpg">' +
                 '<div class="message-timestamp">' +
                 ' <time datetime="" class="timeago uk-text-small">09:22 am</time>' +
                 '</div></div>' +
               ' <div class="message-data">' +
               ' <div class="bubble"></div></div></div>');
         if (((idf == sendr) && (ui == recievr) )||((idf == recievr) && (ui == sendr) )){
               messageElement.find('.bubble').html(message).emoji();
               //ADD MESSAGE

               messageList.append(messageElement);}
           //SCROLL TO BOTTOM OF MESSAGE LIST
              messageList[0].scrollTop = messageList[0].scrollHeight;
   });
  }
  // A helper function to let us set our own state.
  function setUserStatus(status) {
    // Set our status in the list of online users.
    currentStatus = status;
    myUser.set({ id:idf, names: name, firstname:fname, lastname:lname, status: status });
  }
  function getMessageId(snapshot) {
    return snapshot.name().replace(/[^a-z0-9\-\_]/gi,'');
  }
  // Update our GUI to show someone"s online status.
  userListRef.on("child_added", function(snapshot) {
    var user = snapshot.val();

  if (user.names != name) {
         $("<a />")
        .attr({"id": getMessageId(snapshot),"data-username":user.names,"data-fname":user.firstname,"data-lname":user.lastname})
        .html(user.names + "<br />")
        .appendTo("#presenceDiv")
        .click(function(){
           var dt = $(this).attr("data-username"),df=$(this).attr("data-fname"),dl=$(this).attr("data-lname"),
               src="temp/user/"+dt+".jpg";
               $('#chat-avatar').show();
           $('#chat-avatar').attr({'src':src,"data-os":user.status,"data-ui":user.id})
           $('#chat-name').html(df + " " + dl);
           console.log(dt);
         messageList.html(""); 
         getmsg();
    });
        $("<li />")
        .attr({"id": getMessageId(snapshot),"data-username":user.names,"class":"offcanvas-chat-avatar","data-fname":user.firstname,"data-lname":user.lastname})
        .html("<small id='ofstat' data-os="+user.status+" data-ui="+user.id+" ></small><img width='40' height='40' src='temp/user/"+user.names+".jpg'>"+ user.names )
        .appendTo("#clist")
        .click(function(){
                  var dt = $(this).attr("data-username"),df=$(this).attr("data-fname"),dl=$(this).attr("data-lname"),
               src="temp/user/"+dt+".jpg";
                  $('#chat-avatar').show();
           $('#chat-avatar').attr({'src':src,"data-os":user.status,"data-ui":user.id});
           $('#chat-name').html(df + " " + dl);
           console.log(dt);
           messageList.html(""); 
           getmsg();

    });


    }

  });




  // LISTEN FOR KEYPRESS EVENT
  messageField.keypress(function (e) {
    if (e.keyCode == 13) {
      //FIELD VALUES
  //messageList.html(""); 
      var username = nameField;
      var message = messageField.val();
      var ui =  $('#chat-avatar').attr("data-ui");
  if(message != ""){
      //SAVE DATA TO FIREBASE AND EMPTY FIELD

      messagesRef.push({name:username, text:message, sender:idf, reciever:ui});

      }else{
      alert("Text Field Empty");
      }
      //getmsg();

      messageField.val('');

      e.preventDefault();
      // return false;
    } 
  });

我真的需要这个继续工作..已经被困在这里差不多3周了我现在不确定我做的事情是否真的是正确的,但是我能说的是我认为错误在于getmsg()函数虽然不确定...请帮帮我:(

1 个答案:

答案 0 :(得分:1)

您是否尝试使用当前经过身份验证的用户对邮件进行不同的格式设置?这就是调用getMsg()的原因吗?

我会为您提供另一种思考方式,因为它是我设法做的事情,而且我没有这个错误。我认为你的错误来自于.on(&#39; child_added&#39;)无论你是否调用getMsg()都可能被调用。

我的解决方案涉及以下

messagesRef.limit(msgLimit).on('child_added', function (snapshot) {
        var message = snapshot.val();

        //format timestamp from linux epoch to readable format
        var ts = getTimestamp(message.timestamp);

        //gets the image from the user who sent the message
        var userImg = userSnapshot.child(message.userID).child('img').val();

        //variables for message layout
        var chatMsgImg = $('<img>',{class:'avatar', src:userImg});
        var chatMsgDiv = $('<div/>',{class:'message'});
        var chatMsgArrow = $('<span/>', {class:'arrow'});
        var chatMsgName = $('<span/>', {class:'name'}).text(message.from);
        var chatMsgTimestamp = $('<span/>', {class:'datetime'}).text(' '+ts);
        var chatMsgContent = $('<span/>', {class:'body'}).text(message.text);

        //if the message is from the currently signed in user, then align right and use class out
        if((message.userID) == userID){
            var msg = $('<li/>', {class:'out'});
            msg.append(chatMsgImg);
            chatMsgDiv.append(chatMsgArrow);
            chatMsgDiv.append(chatMsgName);
            chatMsgDiv.append(chatMsgTimestamp);
            chatMsgDiv.append(chatMsgContent);
            msg.append(chatMsgDiv);
            msg.appendTo($('#chatDiv'));
        }
        //otherwise align left and use class in
        else{
            var msg = $('<li/>', {class:'in'});
            msg.append(chatMsgImg);
            chatMsgDiv.append(chatMsgArrow);
            chatMsgDiv.append(chatMsgName);
            chatMsgDiv.append(chatMsgTimestamp);
            chatMsgDiv.append(chatMsgContent);
            msg.append(chatMsgDiv);
            msg.appendTo($('#chatDiv'));
        }

        $('#chatDiv')[0].scrollTop = $('#chatDiv')[0].scrollHeight;
    });

通过这种方式,我仍然得到相同的消息细节,但我只是使用输入和输出或传入和传出消息(来自其他用户,分别来自当前用户)将格式保留为CSS