更改频道时,Pubnub会收到重复的消息

时间:2015-06-05 08:46:46

标签: javascript php jquery ajax pubnub

我的pubnub有问题。 我有朋友列表,我需要更改pubnub频道点击它们,切换到另一个朋友,与他聊天。 我有全局频道变量,我在朋友点击时更改它。问题是,当我切换到另一个朋友并写一条消息时,面板中显示的消息是重复的。

这是我正在使用的代码。

base = "/";
pubnub = "";
channel ="";
messageListContent = "ul.chat-messages-block";

function handleMessage(message,$index) {

    if ( $index != 'me' ) {
        var $index = 'left';        
    } else {
        var $index = 'right';                   
    }   

    var $imageUrl = "";
    if ( message.picture != '' && message.picture != null ) {
        $imageUrl = message.picture;

        if ( (/^http:\/\//.test( $imageUrl ) ) ) {
            $imageUrl = $imageUrl;
        } else {
            $imageUrl = "uploads/user/"+ $imageUrl;
        }
    } else {
        $imageUrl = 'resources/images/user-male.png';
    }               

    var messageEl = jQuery('<li class="'+$index+' clearfix">'+
        '<div class="user-img pull-'+$index+'"> <img src="' + $imageUrl +'" alt="'+message.username+'"> </div>'+
        '<div class="chat-body clearfix">'+
            '<div class="">'+
                '<span class="name">'+message.username+'</span><span class="name"></span><span class="badge"><i class="fa fa-clock-o"></i>'+message.chat_date+'</span></div>'+
                '<p>'+ message.message + '</p>'+
            ' </div>'+
        '</li>');

    jQuery(messageListContent).append(messageEl);
};


jQuery.getJSON( "/chat/read", function( data ) {
    var items = [];
    if ( data != null && data != "" ){

        pubnub = PUBNUB.init({
            publish_key: data.publish_key,
            subscribe_key: data.subscribe_key,
        });

        if ( data.messages.length > 0 ) {

            var $my_id = data.current_user; 
            for( var i = 0; i < data.messages.length; i++ ) {

                if ( data.messages[i].user_id == $my_id ) {
                    $index = "me";                      
                } else {
                    var $index = "";                        
                }
                handleMessage(data.messages[i],$index);
            }
        }

    }
});

jQuery(document).ready(function () {    
    jQuery('#sendMessageButton').click(function (event) {
        var message = jQuery('#messageContent').val();
        var friend_id = jQuery('li.activeChannel').attr('data-id');

        if ( message != '' ) {

            jQuery.ajax({
                url:  base+"chat/sendChat",
                type:'POST',
                data:{
                    friend_id: friend_id,
                    text:message
                },
                success:function(data){
                    var data = JSON.parse(data);
                    //sounds.play( 'chat' );

                    pubnub.publish({
                        channel: channel,
                        message: {
                            username: data.messages.username,
                            message: data.messages.message,
                            user_id: data.messages.friend_id,
                            current_user: data.messages.user_id,
                            picture: data.messages.picture,
                            type:'message',
                            chat_date: data.messages.chat_date
                        }
                    });

                },
                error: function(err){
                    jQuery('.errorText').fadeIn();
                }
            });         
            jQuery('#messageContent').val("");

        }
    });



// Also send a message when the user hits the enter button in the text area.
    jQuery('#messageContent').bind('keydown', function (event) {
        if((event.keyCode || event.charCode) !== 13) return true;
        jQuery('#sendMessageButton').click();
        return false;
    });




jQuery('ul.chat-users li').click(function(){
        var friend_id = jQuery(this).attr('data-id');
        jQuery('ul.chat-users li').removeClass('activeChannel');
        jQuery(this).addClass('activeChannel');

        jQuery.ajax({
            url:  base+"chat/getUsersChat",
            type:'POST',
            data:{
                friend_id: friend_id
            },
            success:function(data){
                var data = JSON.parse(data);
                jQuery('.chat-messages ul').html("");
                //id = pubnub.uuid();
                //channel = 'oo-chat-' + id+friend_id;
                channel = 'oo-chat-' + data.channel;

                if ( data.messages.length > 0 ) {

                    var $my_id = data.current_user; 
                    for( var i = 0; i < data.messages.length; i++ ) {

                        if ( data.messages[i].user_id == $my_id ) {
                            $index = "me";                      
                        } else {
                            var $index = "";                        
                        }
                        //messageListContent = "ul.activeChannel"+channel;
                        //console.log(channel);
                        handleMessage(data.messages[i],$index);
                    }
                }

                pubnub.subscribe({
                    channel: channel,
                    message: function(message) {
                        console.log("Pubnub callback", message);
                        handleMessage(message,"me");
                    },   
                    connect: function(message) {
                        console.log("Pubnub is connected", message);
                    },
                    //callback: 
                });

            },
            error: function(err){
                jQuery('.errorText').fadeIn();
            }
        });
    });

});

这就是它的样子

enter image description here

任何想法? 我甚至试图取消订阅朋友点击的上一个频道,但没有结果。 我做错了什么?

1 个答案:

答案 0 :(得分:4)

我解决了这个问题。问题发生在pubnub.js版本中,它是3.4,我切换到3.7.1并添加了以下代码

jQuery('ul.chat-users li').click(function(){
        var friend_id = jQuery(this).attr('data-id');
        jQuery('ul.chat-users li').removeClass('activeChannel');
        jQuery(this).addClass('activeChannel');

        if ( channel != "" ) {
            pubnub.unsubscribe({
                channel : channel,
            });
        }