Search code examples
blockpubnub

publishing events to pubnub blocks from javascript client


I wanted to try out pubnub BLOCKS with a very contrived example. Essentially, I'm publishing a simple message from a client (using javascript sdk) to see if the BLOCK that I've set (or i "think" i've set) to that respective channel is listening...contrived example is failing thus far...

Steps

  1. Create an APP in pubnub to generate credentials.
  2. Included pubnub SDK in simple HTML file, initialized Pubnub, set event listener, and publish/subscribe methods. Set channel to 'hello-world' 2a. Published/Subscribed to messages successfully from different browser windows with .
  3. Went to pubnub debug console and set channel as 'hello-world' to see if messages from 'hello-world' channel would be broadcast and they were not.
  4. From the client, I console logged the object that is returned from messages and the channel is appearing as 'hello-world'..so this left me wondering, why aren't i seeing the messages registered in the pubnub debug console in the same hello-world channel ?

Particularly, my question is: how can i send messages to a pubnub BLOCK from a pubnub CLIENT and send messages from a pubnub BLOCK to a pubnub CLIENT ? or in other words, pub/sub a BLOCK with a CLIENT using the Javascript SDK ?

The simple.js for hello-world example code:

(function(){
  var pubnub = new PubNub({ publishKey : 'p-key', subscribeKey : 's-key' });
  function $(id) { return document.getElementById(id); }
  var box = $('box'), input = $('input'), channel = 'hello-world';
  pubnub.addListener({
      message: function(obj) {
          box.innerHTML = (''+obj.message).replace( /[<>]/g, '' ) + '<br>' + box.innerHTML
      }});
  pubnub.subscribe({channels:[channel]});
  input.addEventListener('keyup', function(e) {
      if ((e.keyCode || e.charCode) === 13) {
        pubnub.publish({channel : channel,message : input.value,x : (input.value='')});
    }
  });
})();

Solution

  • Publishing Messages and Events to PubNub BLOCKS from JavaScript

    I've created an example below which sends messages to PubNub. You can register a BLOCK on the hello-world channel to catch the message.

    1. Register a BLOCK on PubNub. Make sure to start/deploy the block.
    2. Update the publishKey and subscribeKey in the example below.
    3. Run the example below.

    (()=>{
    
        'use strict';
     
        // Initialize PubNub Socket SDK
        const pubnub = new PubNub({ 
            publishKey   : 'demo'
        ,   subscribeKey : 'demo'
        });
    
        // GUI Elements
        const box     = $('#messages')
        ,     input   = $('#message')
        ,     submit  = $('#submit')
        ,     channel = 'hello-world';
    
        // Open Socket to Channels
        pubnub.subscribe({ channels : [channel] });
    
        // When Messages Arrive
        pubnub.addListener({ message: obj => receive_chat(obj) });
    
        // When user sends chat
        submit.click( event => send_chat(input.val()) );
        input.keyup( event => {
            if ((event.keyCode || event.charCode) === 13)
                return send_chat(input.val());
        });
    
        // Draw Chat Messages on Screen
        function receive_chat(obj) {
            box.html((''+obj.message).replace( /[<>]/g, '' )+'<br>'+box.html());
        }
    
        // Send Chat Message
        function send_chat(message) {
            console.log(input.val());
            pubnub.publish({ channel : channel, message : message });
            input.val('');
            return false;
        }
    
    
    })();
    div, input { font-family: "Lucida Grande","Lucida Sans Unicode","Lucida Sans",Geneva,Arial,sans-serif; }
    input { padding: 10px; margin: 10px;  }
    input[type=submit] { width: 100px; line-height: 100px; font-size: 20px;  }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.4.3.min.js"></script>
    
    <input id="message" placeholder="type your message">
    <input id="submit" type="submit" value="Send">
    <div id="messages"></div>