Reputation: 185
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
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='')});
}
});
})();
Upvotes: 1
Views: 497
Reputation: 6834
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.
publishKey
and subscribeKey
in 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>
Upvotes: 1