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
});
The pubnub variable was out scope for the unsubscribe. Developer had to declare pubnub outside the function to unsubscribe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With