Ant*_*wan 7 javascript titanium titanium-mobile pubnub
嘿,我正在使用pubnub服务为我的Titanium App添加聊天功能,但我想知道是否有办法获取未读消息的数量.
在api引用上没有关于此的信息
我试图在历史中保存消息的数量,然后重新加载新的历史记录并计算差异,但它是如此愚蠢和复杂的解决方案,任何人都知道如何实现这一目标?谢谢
多年前我们承诺,我们会在您的应用中使用非常简单的方法来跟踪未读消息计数.现在终于有可能了!使用PubNub函数,您可以将永久状态对象和值添加到多设备应用程序中.您将使用PubNub Functions Key/Value Storage引擎中提供的原子方法.PubNub函数存储引擎(kvstore)被复制到每个数据中心,使其快速可靠地存储/检索数据.
您只需要创建一个函数increment,decrement以及retrieve未读消息的当前计数.
我们的函数将计算发送到通道的消息并使用原子递增和递减方法使用以通道和用户ID命名的键来保存值.这是一种称为"传统命名空间"的实用设计模式.这意味着您将使用消息中的提示和信息来创建基于消息中的信息可构造的名称.我们将在此示例中使用通道名称作为常规名称间距.
第一个函数将递增一个值以跟踪用户收件箱中的未读消息.
渠道:
room.*事件:
On-Before Publish
// Access to Distributed Database
const db = require('kvstore');
export default (request) => {
// Conventionally build the Key ID based on the request parameters and channel name.
let counterId = request.channels[0] + '/' + request.params.uuid;
// Increment or Decrement the unread message counter
let method = request.message.read ? -1 : 1;
// Increment/Decrement and read the unread message counter
return db.incrCounter( counterId, method ).then(()=>{
return db.getCounter(counterId).then((counter) => {
request.message.unread = counter || 0;
return request.ok();
});
});
}
Run Code Online (Sandbox Code Playgroud)
现在,发布到此通道层次结构的任何JSON消息room.*都将通过递增计数器来跟踪未读消息.可以通过包括读标志来递减计数器.如果需要,该读取方法也可以用作读取收据跟踪系统.您可以在Adam Bavosa 的文章中了解有关读取收据的更多信息:阅读实时聊天应用程序的收据模式.
发布如下消息room.john-smith:
{ "message" : "Hello John!" }
Run Code Online (Sandbox Code Playgroud)
John将收到您的消息,并在消息中添加未读消息计数器.该消息将使用unread变量进行扩充.现在消息看起来像这样:
{ "message" : "Hello John!", "unread" : 1 }
Run Code Online (Sandbox Code Playgroud)
约翰可以通过发布回复收据回复:
{ "read" : true }
Run Code Online (Sandbox Code Playgroud)
该消息将使用unread计数器更新已读回执.
{ "read" : true, "unread" : 0 }
Run Code Online (Sandbox Code Playgroud)
而已!你做到了.模式将根据组和一对一消息传递应用程序进行更改.
| 归档时间: |
|
| 查看次数: |
2355 次 |
| 最近记录: |