【问题标题】:Broadcast message only for the owner of the models仅为模型所有者广播消息
【发布时间】:2015-09-18 04:29:02
【问题描述】:

我正在构建一个应用程序,用户可以在其中创建事件,其他用户可以“加入”并将 cmets 添加到事件中,他们也可以在他们之间打开聊天,我有一个名为“通知”的模型,我想在其中存储所有系统中的通知,我想在用户评论他的事件、给他写一条新消息等时向事件的所有者发出警告。

这是我为 cmets 编写的部分代码:

通知模型:

/* Notification.js */
module.exports = {

  attributes: {
    title: {
        type: 'string',
        required: true
    },
    text: {
        type: 'string'
    },
    type:{
        type: 'string',
        enum: ['new_assistant', 'cancel_assistant', 'new_message', 'new_comment'],
        required: 'true'
    },
    read: {
        type: 'boolean',
      defaultsTo: false
    },
    user: {
        model: 'user'
    }
  }
};

这是我为他的通知模型订阅套接字的地方:

Notification.find({
  user: owner_id
}).then(function(notifications) {
  return Notification.watch(req.socket);
});

每当用户对事件发表评论时,我都会创建一个新的通知记录:

Notification.create({
  title: 'A new user has comment',
  text: "Hola",
  type: 'new_comment',
  read: false,
  user: event.owner
}).then(function(comment) {
  return Notification.publishCreate({
    id: notification.id,
    title: 'A new user has comment'
  });
});

该代码运行,但这向所有用户发送了一个套接字消息,我只想警告事件的所有者(以及将来参加此事件的用户)。

非常感谢。

【问题讨论】:

    标签: javascript node.js sockets socket.io sails.js


    【解决方案1】:

    watch 将模型实例创建消息发送到正在观察模型的所有套接字,同样的注册可以在没有找到通知的情况下执行,因为它不依赖于实例,即只需调用:Notification.watch(req.socket);

    要将通知发送给单个订阅者,请使用sails.sockets

    当您想订阅时为所有者创建一个房间:

    sails.sockets.join(req.socket, owner_id);
    

    当你想向这个房间发布广播时:

    Notification.create({
      title: 'A new user has comment',
      text: "Hola",
      type: 'new_comment',
      read: false,
      user: event.owner
    }).then(function(comment) {
      sails.sockets.broadcast(event.owner, {
        id: notification.id,
        title: 'A new user has comment'
      });
    });
    

    【讨论】:

    • 嗨。我实现了你的代码并且它有效。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 2019-09-07
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    相关资源
    最近更新 更多