javascripttwiliodom-eventsinstant-messaging

Twilio IP messaging, how to unsubscribe from channel


I've written a simple chat using Twilio IP messaging example as a starting point. The idea is to have private channels between various clients and admin. Each client will have a separate private channel with admin. Admin can select which channel to open/subscribe to chat with a particular client.

The issue I'm facing now is I cannot unsubscribe from the channel I previously subscribed.

Here is the link to login as admin, client (test1) and client (test2): http://test.verbery.com/

Steps to reproduce the issue:

  1. Click on "Admin (admin1)" to login as admin
  2. On the newly opened admin chat page click on the "test1@qwe.com" channel on the left side panel to subscribe to channel and receive messages for this channel.
  3. On the main page click on "Client (test1)" to login as client and join a channel test1@qwe.com as a client.
  4. Send message from admin to client (test1) and from client (test1) to admin.
  5. On admin chat click on the channel test2@qwe.com to subscribe to this new channel and chat with another client (test2); login as client (test2) and chat with admin.
  6. The problem now is: you are still receiving messages from test1@qwe.com - try to send messages as a test1@qwe.com client. When you subscribed to test2@qwe.com channel, you haven't unsubscribed from test1@qwe.com

Technical details: To subscribe to a channel I used an event "onMessageAdded" to listen to the incoming messages for this channel:

// Listen for new messages sent to the channel
personalChannel.on('messageAdded', function(message) {
    printMessage(message.author, message.body);
});

To unsubscribe from the messages I've tried unbind('onMessageAdded') and off('onMessageAdded') but it doesn't work, js console says: unbind (or off) is not a function.

Any ideas how to unsubscribe from channel?


Solution

  • Twilio developer evangelist here.

    Bob Sponge is right, you need to call leave() on the channel in order to properly leave it.

    personalChannel.leave();
    

    If you are looking to stay connected to the channel, but stop listening from incoming events, you can unbind your listener. You'd actually do that using removeListener rather than off or unbind. This follows the Node.js EventEmitter API.

    personalChannel.removeListener("messageAdded");
    

    Let me know if that helps at all.