4

Just want to understand why my pubnub javascript code does not receive a message from a channel. I can subscribe and publish, but if another browser sends a new publish message, the other browser can not receive the message. heres my code:

$(document).ready(function () {

  var pubnub = PUBNUB.init({
    subscribe_key: 'subscribe-key-here',
    publish_key: 'publish-key-here'
  });

  pubnub.subscribe({
    channel    : "my-channel",
    message    : function(m){ console.log(m) },
    callback   : function (message) { console.log("callback: ", message)},
    connect    : function() {

      console.log("Connected")
      pubnub.publish({
        channel: 'my_channel',
        message: { "color" : "blue" },
        callback : function(details) {
            console.log(details)
        }
      });
     },
     disconnect : function() { console.log("Disconnected") },
     reconnect  : function() { console.log("Reconnected") },
     error      : function() { console.log("Network Error") },
     restore    : true
  })
});

by the way this code is running/testing on my nodejs localhost server and in chrome and firefox browser.

Craig Conover
  • 4,710
  • 34
  • 59

1 Answers1

3

Code Bug - You have a typo in your channel name:

  • subscribe uses my_channel
  • publish uses my-channel

Also, you are using two parameters that mean the same thing in the subscribe: message is an alias for callback

And for your publish, success is an alias (in JavaScript/Node v3.7.20+) for callback and it recommended (just because it makes more sense).

I have removed the callback parameter from your subscribe and replace callback with success in your code below.

Corrected code:

$(document).ready(function () {

  var pubnub = PUBNUB.init({
    subscribe_key: 'subscribe-key-here',
    publish_key: 'publish-key-here'
  });

  pubnub.subscribe({
    channel    : "my_channel",
    message    : function (message) { console.log("callback: ", message)},
    connect    : function() {

      console.log("Connected")
      pubnub.publish({
        channel: 'my_channel',
        message: { "color" : "blue" },
        success : function(details) {
            console.log(details)
        }
      });
     },
     disconnect : function() { console.log("Disconnected") },
     reconnect  : function() { console.log("Reconnected") },
     error      : function() { console.log("Network Error") },
     restore    : true
  })
});
Craig Conover
  • 4,710
  • 34
  • 59