我知道这很旧,但我不得不再次解决这个问题,并且不喜欢重复代码的想法,所以如果有人正在寻找替代方案,诀窍是更新新创建记录的模型使用 afterCreate: 方法。
假设您有一款游戏想要让您的玩家订阅。游戏有通知,一组文本警报,您只希望游戏中的玩家收到。为此,请通过请求在客户端订阅 Game。在这里,我通过调用 game/gameId 来获取特定游戏,然后根据模型上已有的通知和玩家构建我的页面:
io.socket.get('/game/'+gameId, function(resData, jwres) {
let players = resData.players;
let notifications = resData.notifications;
$.each(players, function (k,v) {
if(v.id!=playerId){
addPartyMember(v);
}
});
$.each(notifications, function (k,v) {
addNotification(v.text);
});
});
我们知道,订阅游戏只会给出 id,但是当我添加通知时,我同时拥有游戏 Id 和通知记录,因此我可以在 Notification 模型中添加以下内容:
afterCreate: function (newlyCreatedRecord, cb) {
Game.publishAdd(newlyCreatedRecord.game,'notifications',newlyCreatedRecord);
cb();}
由于我原来的 socket.get 订阅了一个特定的游戏,我只能使用 Game.publishAdd() 向那些订阅者发布。现在回到客户端,监听返回的数据:
io.socket.on('game', function (event) {
if (event.attribute == 'notifications') {
addNotification(event.added.text);
}
});
传入的记录将如下所示:
{"id":"59fdd1439aee4e031e61f91f",
"verb":"addedTo",
"attribute" :"notifications",
"addedId":"59fef31ba264a60e2a88e5c1",
"added":{"game":"59fdd1439aee4e031e61f91f",
"text":"some messages",
"createdAt":"2017-11-05T11:16:43.488Z",
"updatedAt":"2017-11-05T11:16:43.488Z",
"id":"59fef31ba264a60e2a88e5c1"}}