Search code examples
javascriptpubnubreal-time-data

upgrade from pubnub javascript v3 to v4, where and how to add listeners?


I am updating from pubnub v3 javascript to v4, the publish and subscribe is working, but do not update the database in live... I readed the migration topic here, but I dont understand how, and where I have to integrate the listeners function, I think that is the problem.

var pubnub = new PubNub({
                subscribeKey : 'xxx',
                publishKey : 'zzz',
                ssl: true
            });

pubnub.subscribe({
    channels : ['my_channel'],
    message : function( message, env, channel ){
        var getMessage = JSON.stringify(message);
// I readed that I should remove stringify
// to: var getMessage = message;
            var obj = jQuery.parseJSON(getMessage);
            var data = setInterval(function(){ removeTdBorder(); }, 3000);
... other functions ...
});

and the publish function

function saveToDatabase(editableObj,column,id) {

    if(editableObj.tagName == "TD")
    {
        var editval = editableObj.innerHTML;
    }else{
        var editval = jQuery('[name="'+column+'"]').val();
    }

    pubnub.publish({
        channel: 'my_channel',        
        message:    {
                        "message" : editval,
                        "column"  : column,
                        "id"      : id,
                    },
        callback : function(m){
        }
    });

I have a table component, where I insert data to the cells, with pubnub real time javascript api. I appreciate any help! Thank you in advance!


Solution

  • PubNub v4 SDK Listeners

    There is no db update feature in PubNub. To answer the how to listen to messages question, there is no callback in subscribe anymore. You receive messages in the addListener callbacks.

    See this addListener API Ref for details. I think the issue is that the migration guide doesn't have any sample addListener code. Here is the sample code from the docs:

    pubnub.addListener({
        message: function(m) {
            // handle message
            var channelName = m.channel; 
            var pubTT = m.timetoken; // Publish timetoken
            var msg = m.message; 
        }
    })