Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pubnub receiving duplicate messages

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
 });
like image 864
Citylogic Avatar asked Feb 12 '14 08:02

Citylogic


1 Answers

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

like image 89
2 revs Avatar answered Sep 26 '22 04:09

2 revs