nowjs group leave event called multiple times

2019-07-31 17:13发布

问题:

I am using now.js groups and want to listen for when a user leaves a group so I can perform some tidying up if the group is empty. I find that the leave event is called multiple times for each time a user has been in a group, i.e. if I join a group and close my browser 3 times on the 3rd time leave will be called 3 times.

chatserver.prototype.joinGroup = function(groupId) {
   //user joins group
   var group = this.nowjs.getGroup(doc_id);
   group.addUser(that.user.clientId);

   //want to know when a user leaves a group
   group.on('leave', function() {
       console.log("user left group:"+groupId)
       //do group clean up
   });
};

Am I doing something wrong with scoping?

回答1:

You should remove every user from the group it has been connected to, on disconnect.

Something like :

nowjs.on('disconnect', function() { 
        var that = this;
        this.getGroups( function(groups) {
             for ( i=0 ; i < groups.length; i++ ) {
                 nowjs.getGroup(groups[i]).removeUser(that.user.clientId);
             }
        }
}