Pubnub receiving duplicate messages
Asked Answered
O

1

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
 });
Osteotomy answered 12/2, 2014 at 8:12 Comment(6)
I should add the message is being sent one, and received multiple times - if I reload the app the history does not contain duplicates.Osteotomy
pubnub.unsubscribe({channel : 'my_channel' }); does not work?Nailbrush
I tried putting it in the close: function() but the view doesn't close. I'm not sure where else I should be unsubscribing.Osteotomy
Thanks! I got it working - I had to declare pubnub outside the function to unsubscribe. Learning as I go.Osteotomy
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 subscribingNailbrush
It wasn't working before subscribing, but I got it to work in the view close function. Thanks for the help!Osteotomy
J
3

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

Judaism answered 12/2, 2014 at 8:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.