Unsubscribe Pusher channel

8.2k Views Asked by At

I'm new to using Pusher with my Rails app. Everything is working fine and i'm now able to subscribe to channels and receive JSON message.

But i want to make an button where i can unsubscribe from a specific channel.

I have tried this

<button onclick="unsubscribe_channcel('test_channel')">Unsubscribe</button>

<script>
  function unsubscribe_channcel(channelName) {
  var pusher = new Pusher('APP KEY');
  pusher.unsubscribe(channelName);
};
</script>

But it do not work. If i look in the debug console when i press the button all that happens is that it make a new connection and i keep receiving messages from the "test_channel".

1

There are 1 best solutions below

3
On BEST ANSWER

You need to unsubscribe to the channel on the same instance of the Pusher object that you subscribed to the channel on e.g.

<button onclick="subscribe_channel('test_channel')">Subscribe</button>
<button onclick="unsubscribe_channel('test_channel')">Unsubscribe</button>

<script src="http://js.pusher.com/2.2/pusher.min.js"></script>
<script>
  Pusher.log = function(msg){
    console.log(msg);
  };

  var YOUR_APP_KEY = "1afb3f8f61eb29da86df";
  var pusher = new Pusher(YOUR_APP_KEY);

  function subscribe_channel( channelName ) {
    pusher.subscribe( channelName );
  }

  function unsubscribe_channel(channelName) {
    pusher.unsubscribe(channelName);
  }
</script>

You can find a working example of this code here: http://jsbin.com/camul/1/edit?html,console,output