6

I am using PubNub for in-app chat with Backbone and the javascript sdk. If I navigate to another view and return to the chat window, when I publish a message I receive it in duplicate. If I browse away again I receive messages in triplicate and so on..

I think I am subscribing again and again each time I return to the chat page - but I can't get the unsubscribe to work and I can't find any documentation on where else to subscribe from.

Is there a check I can use to see if I am already subscribed?

My code is:

// INIT
var channel = 'my_channel';
var pubnub  = PUBNUB.init({
subscribe_key : 'demo',
publish_key   : 'demo'
});

function chat(message) {
if (message.uid == "xxx") {
    $("#convo").append('<div class="isaid">' + message.message + '</div><div class="clear clearfix"></div>');
} else {
    $("#convo").append('<div class="hesaid">' + message.message + '</div><div class="clear clearfix"></div>');
}
}

pubnub.history({
channel  : channel, // USER_ID Channel
limit    : 30,      // Load Last 50 Messages
callback : function(msgs) { 
    pubnub.each( msgs[0], chat );
}
});

pubnub.subscribe({
channel: 'my_channel',
callback: function(data) {
    chat(data);
}
});

pubnub.publish({
     channel: 'my_channel',        
     message: data
 });
Citylogic
  • 113
  • 2
  • 8
  • 1
    I should add the message is being sent one, and received multiple times - if I reload the app the history does not contain duplicates. – Citylogic Feb 12 '14 at 08:20
  • `pubnub.unsubscribe({channel : 'my_channel' });` does not work? – sb9 Feb 12 '14 at 08:22
  • 1
    I tried putting it in the `close: function()` but the view doesn't close. I'm not sure where else I should be unsubscribing. – Citylogic Feb 12 '14 at 09:55
  • Thanks! I got it working - I had to declare pubnub outside the function to unsubscribe. Learning as I go. – Citylogic Feb 12 '14 at 10:10
  • You can try to `unsubscribe()` from a `window.onunload` (or `$(window).unload` handler. If this also does not work you still can try to call `unsubscribe` before subscribing – sb9 Feb 12 '14 at 10:10
  • 1
    It wasn't working before subscribing, but I got it to work in the view close function. Thanks for the help! – Citylogic Feb 12 '14 at 13:48

1 Answers1

3

The pubnub variable was out scope for the unsubscribe. Developer had to declare pubnub outside the function to unsubscribe.

Craig Conover
  • 4,710
  • 34
  • 59