1

我的聊天消息显示如下:

  {{#each msg}}
    {{> chatMsg}}
  {{/each}}

当用户进入聊天时,我将文档添加到集合中user joins the chat。当用户快速重新进入并离开聊天时,我不想user joins the chat一遍又一遍地重复。我想显示类似user joins the chat x3.

有没有办法通过连接到 renderList 在客户端做到这一点?我知道我可以在服务器端更改文档,但它似乎不必要地密集。

4

2 回答 2

1

从这里到达那里的最简单方法是编写自定义发布者。不只是从发布函数返回一个游标,而是在发布函数中对游标调用 observe(),并在其中执行适当的 set()、unset() 和 flush() 调用,以适当地乘以前一个消息而不是添加新消息。您可以在Meteor.publish 的流星文档中找到相关文档

要从比较中获得基础,您可以查看当前发布 Cursor 的代码,该代码位于 packages/mongo-livedata/mongo_driver.js 中,位于 Cursor.prototype._publishCursor 中。

注意:我的回答是针对 Meteor 0.5.2。自定义发布者的 API 将在 Meteor 的未来版本中发生变化,您必须调用的函数不同于 set() unset() 和 flush()

于 2012-12-14T02:05:17.107 回答
0

一种选择是进行仅更新最新用户加入消息的方法调用。

function formatJoinMessage(username,count) {...}

if (Meteor.isServer) Meteor.startup(function () {Chats._ensureIndex({modified:-1}); ...});

Meteor.methods({
    join:function() {
        var joinMessage = Chats.find({type:MESSAGE_TYPE_JOINED,userId:this.userId}).sort({modified:-1}).fetch()[0];
        if (joinMessage)
            Chats.update({_id:joinMessage._id},{$inc:{joins:1},$set:{text:formatJoinMessage(this.userId,joinMessage.joins+1),modified:new Date()});
        else
            Chats.insert({user:this.userId,joins:1,modified:new Date(),text:formatJoinMessage(this.userId,1)});
    }
)};

不想更改服务器文档?没关系,但从概念上讲,聊天加入不是聊天消息。因此,您绝对应该在文档meta中包含此类内容的字段。chat

但假设你不想这样做。我会做这样的事情:

var userIdToName = function(userId) {...}; // some kind of userId to name helper

Template.chatroom.msg = function() {
  var messages = Chat.findOne(Session.get("currentChat")).messages; // msg in your code?
  return _.reduce(messages,function (newMessages, currentMessage) {
    var lastMsg = newMessages[newMessages.length-1];
    if (currentMessage.type == MESSAGE_TYPES_JOIN) {
       if (lastMsg && lastMsg.type == MESSAGE_TYPES_JOIN && currentMessage.user == lastMsg.user) {
          currentMessage.timesJoined = lastMsg.timesJoined+1;
          newMessages.shift();
       } else {
          currentMessage.timesJoined = 1;
       }
       currentMessage.chatMsg = userIdToName(lastMsg.user) + " joins the chat &mult;" + currentMessage.timesJoined.toString();
    }
    return newMessages.concat(currentMessage);
  },[]);
}

这有点笨拙。可以这么说,它将在聊天的当前消息中找到的所有加入消息“减少”为一条消息。您动态添加属性timesJoined;它没有出现在文档中。但是您应该有一个type字段让您知道加入消息和常规消息之间的区别。

如果您至少没有该元数据,那么您的聊天应用程序将无法正常工作。不要犹豫,改变你的模型!

于 2012-12-17T09:19:33.553 回答