【问题标题】:Swampdragon: how to determine a channel the message was published to?Swampdragon:如何确定消息发布到的频道?
【发布时间】:2016-01-20 10:38:11
【问题描述】:

在我的项目后端发送大量消息发布到不同的渠道。
我可以从浏览器控制台看到到达的消息具有channel 属性。 但问题是传递给swampdragon.onChannelMessage 的回调没有获得该频道信息。它会得到奇怪的频道列表。
因此,当消息到达(在浏览器中)时,我无法确定它发布到的频道,因此无法正确处理它。

我找到了删除频道信息的代码https://github.com/jonashagstedt/swampdragon/blob/master/swampdragon/static/swampdragon/js/dist/swampdragon.js#L261

if ('channel' in e.data) {
  var channel = swampDragon.channels[e.data.channel];
  delete(e.data['channel']);
  swampDragon.settings.onchannelmessage(channel, e.data);
  return;
}

所以我的问题是前端开发人员如何确定到达的消息发布到哪个频道,以便能够正确处理消息?

【问题讨论】:

    标签: javascript sockets websocket swampdragon


    【解决方案1】:

    有点晚了,但万一你无法解决这个问题:

    swampdragon.open(function() {
      swampdragon.subscribe('notification', 'notification', null, function (context, data) {
        // Successfully subscribed to the notification channel
      }, function () {
        console.error('Error', arguments);
      });
    });
    
    swampdragon.onChannelMessage(function(channels, message) {
      if (channels.indexOf('notification') > -1) {
        // Message sent on the notification channel
      }
    });
    

    onChannelMessage 中,channels 参数是传入消息发送到的通道数组。您可以使用indexOf查看您感兴趣的频道是否在列表中。

    【讨论】: