我不熟悉在Pusher应用程序中使用Rails的情况。
一切正常,我现在可以订阅频道并接收JSON消息。

但是我想创建一个按钮,可以在其中取消订阅特定频道。

我已经试过了

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

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


但这不起作用。如果我在按下按钮时在调试控制台中查看,则发生的一切是它建立了新的连接,并且我不断接收来自“ test_channel”的消息。

最佳答案

您需要在Pusher对象的同一实例上取消订阅该频道,例如,您已在该频道上订阅了该频道。

<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>


您可以在此处找到此代码的有效示例:http://jsbin.com/camul/1/edit?html,console,output

08-17 19:22