仅在Firebase中显示带有RoomID的邮件

时间:2015-11-03 19:08:53

标签: javascript firebase

我正在尝试使用单独的房间创建FireBase聊天,并且只显示来自该房间的消息。如何才能显示roomid = somenumber(目前设为4)

的讯息

数据可能如下所示:

enter image description here

这是firebase文档之后的代码。

<body>

<!-- CHAT MARKUP -->
<div class="example-chat l-demo-container">
  <header>Firebase Chat Demo</header>

  <div class='example-chat-toolbar'>
    <label for="nameInput">Username:</label>
    <input type='text' id='nameInput' placeholder='enter a username...'>
  </div>

  <ul id='example-messages' class="example-chat-messages"></ul>

  <footer>
    <input type='text' id='messageInput'  placeholder='Type a message...'>
  </footer>
</div>

<!-- CHAT JAVACRIPT -->
<script>
  // CREATE A REFERENCE TO FIREBASE
  var messagesRef = new Firebase('https://blistering-fire-1740.firebaseio.com/');

  // REGISTER DOM ELEMENTS
  var messageField = $('#messageInput');
  var nameField = $('#nameInput');
  var messageList = $('#example-messages');

  // LISTEN FOR KEYPRESS EVENT
  messageField.keypress(function (e) {
    if (e.keyCode == 13) {
      //FIELD VALUES
      var username = nameField.val();
      var message = messageField.val();

      //SAVE DATA TO FIREBASE AND EMPTY FIELD
      messagesRef.push({name:username, text:message, roomid:4});
      messageField.val('');
    }
  });

  // Add a callback that is triggered for each chat message.
  messagesRef.limitToLast(10).on('child_added', function (snapshot) {
    //GET DATA
    var data = snapshot.val();
    var username = data.name || "anonymous";
    var message = data.text;

    //CREATE ELEMENTS MESSAGE & SANITIZE TEXT
    var messageElement = $("<li>");
    var nameElement = $("<strong class='example-chat-username'></strong>")
    nameElement.text(username);
    messageElement.text(message).prepend(nameElement);

    //ADD MESSAGE
    messageList.append(messageElement)

    //SCROLL TO BOTTOM OF MESSAGE LIST
    messageList[0].scrollTop = messageList[0].scrollHeight;
  });
</script>
</body>

firebase doc

2 个答案:

答案 0 :(得分:3)

Dan的回答可行,但这意味着您要下载所有聊天消息。如果您不下载不需要的数据,小型数据计划的用户将会很感激:

var roomMessages = messagesRef.orderByChild('roomid').equalTo(4);
roomMessages.limitToLast(10).on('child_added', function (snapshot) {
    //GET DATA
    var data = snapshot.val();

您需要roomid上的索引,如here所述。

答案 1 :(得分:1)

将这些消息添加到DOM时,只需过滤掉不属于该房间的消息。

// Add a callback that is triggered for each chat message.
messagesRef.limitToLast(10).on('child_added', function (snapshot) {
  var data = snapshot.val();

  // break out of the function early if this message does not
  // belong in this room.
  if(data.roomId !== 4) return;

  var username = data.name || "anonymous";
  var message = data.text;

  // ...
});

您可能不希望将roomID硬编码到代码中。将当前房间ID存储在某处的变量中是有意义的,然后检查它。

  var currentRoomId = getRoomId(); // get from URL, or from Firebase
  // ...
  if(data.roomId !== currentRoomId) return;