1

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?

henry.oswald
  • 5,304
  • 13
  • 51
  • 73
  • The problem is definitely in your group array, do you call group.removeUser anywhere in your code ? If no try to trigger `group.removeUser(that.user.clientId)` on nowjs disconnect event! – drinchev Apr 22 '12 at 12:14
  • I tried that inside of the leave callback however removeUser triggers the leave event so you get stuck in a loop. – henry.oswald Apr 22 '12 at 13:04
  • I meant disconnect event smth. like : `nowjs.on('disconnect', function() { group.removeUser(this.user.clientId) });`. If you don't have any removeUser, what causes the leave event of the group in your original code? – drinchev Apr 22 '12 at 13:07
  • The leave is caused either by the window being closed or using the chat room metaphor they change room. In your example is how do you get reference to the right group? The user may be inside 4 groups but they only want to leave one group. – henry.oswald Apr 22 '12 at 13:13
  • I'm writing it as an answer, because there is too much code! – drinchev Apr 22 '12 at 13:21

1 Answers1

0

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);
             }
        }
}
drinchev
  • 19,201
  • 4
  • 67
  • 93
  • Thank you for the help. This seems like a work around meaning the 'leave' event is unusable. It also does not allow the user to leave just one group which I need to do. – henry.oswald Apr 22 '12 at 13:24
  • IMHO, you should remove the user from the groups he is in, when he disconnects, because on every connect you are placing him in the group(s) again... leave event is still on for example if someone leaves the group on purpose ( not by disconnecting ). – drinchev Apr 22 '12 at 13:28
  • 2
    I believe now removes the user from all groups upon disconnection anyway. What I really need is to do clean up of a the group if someone leaves. – henry.oswald Apr 22 '12 at 13:40