Get Code:
Get Code: CDN
Latest version
Latest minified version
Get Code: Source
View Supported Platforms
Hello World
You must include the PubNub JavaScript SDK in your code before initializing the client.
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.27.1.js"></script>
Example
function publish() {
pubnub = new PubNub({
publishKey : 'demo',
subscribeKey : 'demo'
})
function publishSampleMessage() {
console.log("Since we're publishing on subscribe connectEvent, we're sure we'll receive the following publish.");
var publishConfig = {
channel : "hello_world",
message: {
title: "greeting",
description: "hello world!"
}
}
pubnub.publish(publishConfig, function(status, response) {
console.log(status, response);
})
}
pubnub.addListener({
status: function(statusEvent) {
if (statusEvent.category === "PNConnectedCategory") {
publishSampleMessage();
}
},
message: function(msg) {
console.log(msg.message.title);
console.log(msg.message.description);
},
presence: function(presenceEvent) {
// handle presence
}
})
console.log("Subscribing..");
pubnub.subscribe({
channels: ['hello_world']
});
};
Copy and paste examples
Init
Instantiate a new Pubnub instance. Only the subscribeKey
is mandatory. Also include publishKey
if you intend to publish from this instance, and the secretKey
if you wish to perform PAM administrative operations from this JavaScript V4 instance.
It is not a best practice to include the When you init with |
Set restore as true to allow catch up on the front-end applications. |
Initializing the client
var pubnub = new PubNub({
subscribeKey: "mySubscribeKey",
publishKey: "myPublishKey",
ssl: true
})
Listeners
Adding Listeners
pubnub.addListener({
message: function(m) {
// handle message
var channelName = m.channel; // The channel for which the message belongs
var channelGroup = m.subscription; // The channel group or wildcard subscription match (if exists)
var pubTT = m.timetoken; // Publish timetoken
var msg = m.message; // The Payload
var publisher = m.publisher; //The Publisher
},
presence: function(p) {
// handle presence
var action = p.action; // Can be join, leave, state-change or timeout
var channelName = p.channel; // The channel for which the message belongs
var occupancy = p.occupancy; // No. of users connected with the channel
var state = p.state; // User State
var channelGroup = p.subscription; // The channel group or wildcard subscription match (if exists)
var publishTime = p.timestamp; // Publish timetoken
var timetoken = p.timetoken; // Current timetoken
var uuid = p.uuid; // UUIDs of users who are connected with the channel
},
signal: function(s) {
// handle signal
var channelName = s.channel; // The channel for which the signal belongs
var channelGroup = s.subscription; // The channel group or wildcard subscription match (if exists)
var pubTT = s.timetoken; // Publish timetoken
var msg = s.message; // The Payload
var publisher = s.publisher; //The Publisher
},
user: function(userEvent) {
// for Objects, this will trigger when:
// . user updated
// . user deleted
},
space: function(spaceEvent) {
// for Objects, this will trigger when:
// . space updated
// . space deleted
},
membership: function(membershipEvent) {
// for Objects, this will trigger when:
// . user added to a space
// . user removed from a space
// . membership updated on a space
},
messageAction: function(ma) {
// handle message action
var channelName = ma.channel; // The channel for which the message belongs
var publisher = ma.publisher; //The Publisher
var event = ma.message.event; // message action added or removed
var type = ma.message.data.type; // message action type
var value = ma.message.data.value; // message action value
var messageTimetoken = ma.message.data.messageTimetoken; // The timetoken of the original message
var actionTimetoken = ma.message.data.actionTimetoken; //The timetoken of the message action
},
status: function(s) {
var affectedChannelGroups = s.affectedChannelGroups; // The channel groups affected in the operation, of type array.
var affectedChannels = s.affectedChannels; // The channels affected in the operation, of type array.
var category = s.category; //Returns PNConnectedCategory
var operation = s.operation; //Returns PNSubscribeOperation
var lastTimetoken = s.lastTimetoken; //The last timetoken used in the subscribe request, of type long.
var currentTimetoken = s.currentTimetoken; //The current timetoken fetched in the subscribe response, which is going to be used in the next request, of type long.
var subscribedChannels = s.subscribedChannels; //All the current subscribed channels, of type array.
}
});
Removing Listeners
var existingListener = {
message: function() {
}
}
pubnub.removeListener(existingListener)
listeners status events
Categories | Description |
---|---|
PNNetworkUpCategory | SDK detected that network is online. |
PNNetworkDownCategory | The SDK will announce this when connection is not available or this is not able to reach the PubNub Data Stream Network. |
PNNetworkIssuesCategory | A subscribe event experienced an exception when running. The SDK is not being to able reach the PubNub Data Stream Network because the machine or device are not connected to Internet or this has been lost, your ISP (Internet Service Provider) is having to troubles or perhaps or the SDK is behind of a proxy. |
PNReconnectedCategory | SDK was able to reconnect to pubnub. |
PNConnectedCategory | SDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed). |
PNAccessDeniedCategory | PAM permission failure. |
PNMalformedResponseCategory | JSON parsing crashed. |
PNBadRequestCategory | The server responded with bad response because the request is malformed. |
PNDecryptionErrorCategory | If using decryption strategies and the decryption fails. |
PNTimeoutCategory | Failure to establish connection due to timeout. |
PNRequestMessageCountExceedCategory | The SDK will announce this error if requestMessageCountThreshold is set and the number of messages arrived from (PubNub in memory cache messages) are greater than this. |
PNUnknownCategory | This status code is returned when the subscriber get’s a non 200 HTTP response code from the server. |
Time
time()
to verify the client connectivity to the origin:// assuming an initialized PubNub instance already exists
pubnub.time(function(status, response) {
if (status.error) {
// handle error if something went wrong based on the status object
} else {
console.log(response.timetoken);
}
})
Subscribe
Subscribe (listen on) a channel
pubnub.subscribe({
channels: ['my_channel'],
});
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method. |
Publish
pubnub.publish(
{
message: {
such: 'object'
},
channel: 'ch1',
sendByPost: false, // true to send via POST
storeInHistory: false, //override default storage options
meta: {
"cool": "meta"
} // publish extra meta with the request
},
function (status, response) {
// handle status, response
}
);
Here Now
here now
on the channel by UUID:Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys |
pubnub.hereNow(
{
channels: ["ch1"],
channelGroups : ["cg1"],
includeUUIDs: true,
includeState: true
},
function (status, response) {
// handle status, response
}
);
Presence
join
, leave
, and timeout
, by UUID. Setting the presence attribute to a callback will subscribe to presents events on my_channel
:Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys |
pubnub.subscribe({
channels: ['my_channel'],
withPresence: true
});
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method. |
History
Requires that the Storage and Playback add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys |
pubnub.history(
{
channel: 'history_channel',
count: 100, // how many items to fetch
stringifiedTimeToken: true, // false is the default
},
function (status, response) {
// handle status, response
}
);
Unsubscribe
Stop subscribing (listening) to a channel.
pubnub.unsubscribe({
channels: ['my_channel']
})
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method. |
Get Code:
Get Code: Source
View Supported Platforms
Hello World
You must include the PubNub JavaScript SDK in your code before initializing the client.
var PubNub = require('pubnub')
Example
function publish() {
pubnub = new PubNub({
publishKey : 'demo',
subscribeKey : 'demo'
})
function publishSampleMessage() {
console.log("Since we're publishing on subscribe connectEvent, we're sure we'll receive the following publish.");
var publishConfig = {
channel : "hello_world",
message : {
title: "greeting",
description: "hello world!"
}
}
pubnub.publish(publishConfig, function(status, response) {
console.log(status, response);
})
}
pubnub.addListener({
status: function(statusEvent) {
if (statusEvent.category === "PNConnectedCategory") {
publishSampleMessage();
}
},
message: function(msg) {
console.log(msg.message.title);
console.log(msg.message.description);
},
presence: function(presenceEvent) {
// handle presence
}
})
console.log("Subscribing..");
pubnub.subscribe({
channels: ['hello_world']
});
};
Copy and paste examples
Init
Instantiate a new Pubnub instance. Only the subscribeKey
is mandatory. Also include publishKey
if you intend to publish from this instance, and the secretKey
if you wish to perform PAM administrative operations from this Node.js V4 instance.
It is not a best practice to include the When you init with |
Set restore as true to allow catch up on the front-end applications. |
Initializing the client
// PubNub = require('pubnub'); ES5
import PubNub from 'pubnub'; ES6
var pubnub = new PubNub({
subscribeKey: "mySubscribeKey",
publishKey: "myPublishKey",
secretKey: "secretKey",
ssl: true
})
Listeners
Adding Listeners
pubnub.addListener({
message: function(m) {
// handle message
var channelName = m.channel; // The channel for which the message belongs
var channelGroup = m.subscription; // The channel group or wildcard subscription match (if exists)
var pubTT = m.timetoken; // Publish timetoken
var msg = m.message; // The Payload
var publisher = m.publisher; //The Publisher
},
presence: function(p) {
// handle presence
var action = p.action; // Can be join, leave, state-change or timeout
var channelName = p.channel; // The channel for which the message belongs
var occupancy = p.occupancy; // No. of users connected with the channel
var state = p.state; // User State
var channelGroup = p.subscription; // The channel group or wildcard subscription match (if exists)
var publishTime = p.timestamp; // Publish timetoken
var timetoken = p.timetoken; // Current timetoken
var uuid = p.uuid; // UUIDs of users who are connected with the channel
},
signal: function(s) {
// handle signal
var channelName = s.channel; // The channel for which the signal belongs
var channelGroup = s.subscription; // The channel group or wildcard subscription match (if exists)
var pubTT = s.timetoken; // Publish timetoken
var msg = s.message; // The Payload
var publisher = s.publisher; //The Publisher
},
user: function(userEvent) {
// for Objects, this will trigger when:
// . user updated
// . user deleted
},
space: function(spaceEvent) {
// for Objects, this will trigger when:
// . space updated
// . space deleted
},
membership: function(membershipEvent) {
// for Objects, this will trigger when:
// . user added to a space
// . user removed from a space
// . membership updated on a space
},
messageAction: function(ma) {
// handle message action
var channelName = ma.channel; // The channel for which the message belongs
var publisher = ma.publisher; //The Publisher
var event = ma.message.event; // message action added or removed
var type = ma.message.data.type; // message action type
var value = ma.message.data.value; // message action value
var messageTimetoken = ma.message.data.messageTimetoken; // The timetoken of the original message
var actionTimetoken = ma.message.data.actionTimetoken; //The timetoken of the message action
},
status: function(s) {
var affectedChannelGroups = s.affectedChannelGroups; // The channel groups affected in the operation, of type array.
var affectedChannels = s.affectedChannels; // The channels affected in the operation, of type array.
var category = s.category; //Returns PNConnectedCategory
var operation = s.operation; //Returns PNSubscribeOperation
var lastTimetoken = s.lastTimetoken; //The last timetoken used in the subscribe request, of type long.
var currentTimetoken = s.currentTimetoken; //The current timetoken fetched in the subscribe response, which is going to be used in the next request, of type long.
var subscribedChannels = s.subscribedChannels; //All the current subscribed channels, of type array.
}
});
Removing Listeners
var existingListener = {
message: function() {
}
}
pubnub.removeListener(existingListener)
listeners status events
Categories | Description |
---|---|
PNNetworkUpCategory | SDK detected that network is online. |
PNNetworkDownCategory | The SDK will announce this when connection is not available or this is not able to reach the PubNub Data Stream Network. |
PNNetworkIssuesCategory | A subscribe event experienced an exception when running. The SDK is not being to able reach the PubNub Data Stream Network because the machine or device are not connected to Internet or this has been lost, your ISP (Internet Service Provider) is having to troubles or perhaps or the SDK is behind of a proxy. |
PNReconnectedCategory | SDK was able to reconnect to pubnub. |
PNConnectedCategory | SDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed). |
PNAccessDeniedCategory | PAM permission failure. |
PNMalformedResponseCategory | JSON parsing crashed. |
PNBadRequestCategory | The server responded with bad response because the request is malformed. |
PNDecryptionErrorCategory | If using decryption strategies and the decryption fails. |
PNTimeoutCategory | Failure to establish connection due to timeout. |
PNRequestMessageCountExceedCategory | The SDK will announce this error if requestMessageCountThreshold is set and the number of messages arrived from (PubNub in memory cache messages) are greater than this. |
PNUnknownCategory | This status code is returned when the subscriber get’s a non 200 HTTP response code from the server. |
Time
time()
to verify the client connectivity to the origin:// assuming an initialized PubNub instance already exists
pubnub.time(function(status, response) {
if (status.error) {
// handle error if something went wrong based on the status object
} else {
console.log(response.timetoken);
}
})
Subscribe
Subscribe (listen on) a channel
pubnub.subscribe({
channels: ['my_channel'],
});
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method. |
Publish
pubnub.publish(
{
message: {
such: 'object'
},
channel: 'ch1',
sendByPost: false, // true to send via POST
storeInHistory: false, //override default storage options
meta: {
"cool": "meta"
} // publish extra meta with the request
},
function (status, response) {
// handle status, response
}
);
Here Now
here now
on the channel by UUID:Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys |
pubnub.hereNow(
{
channels: ["ch1"],
channelGroups : ["cg1"],
includeUUIDs: true,
includeState: true
},
function (status, response) {
// handle status, response
}
);
Presence
join
, leave
, and timeout
, by UUID. Setting the presence attribute to a callback will subscribe to presents events on my_channel
:Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys |
pubnub.subscribe({
channels: ['my_channel'],
withPresence: true
});
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method. |
History
Requires that the Storage and Playback add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys |
pubnub.history(
{
channel: 'history_channel',
count: 100, // how many items to fetch
stringifiedTimeToken: true, // false is the default
},
function (status, response) {
// handle status, response
}
);
Unsubscribe
Stop subscribing (listening) to a channel.
pubnub.unsubscribe({
channels: ['my_channel']
})
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method. |
Get Code:
Get Code: CDN
Latest version
Latest minified version
Get Code: Source
View Supported Platforms
Hello World
You must include the PubNub JavaScript SDK in your code before initializing the client.
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.27.1.js"></script>
Example
function publish() {
pubnub = new PubNub({
publishKey : 'demo',
subscribeKey : 'demo'
})
function publishSampleMessage() {
console.log("Since we're publishing on subscribe connectEvent, we're sure we'll receive the following publish.");
var publishConfig = {
channel : "hello_world",
message: {
title: "greeting",
description: "hello world!"
}
}
pubnub.publish(publishConfig, function(status, response) {
console.log(status, response);
})
}
pubnub.addListener({
status: function(statusEvent) {
if (statusEvent.category === "PNConnectedCategory") {
publishSampleMessage();
}
},
message: function(msg) {
console.log(msg.message.title);
console.log(msg.message.description);
},
presence: function(presenceEvent) {
// handle presence
}
})
console.log("Subscribing..");
pubnub.subscribe({
channels: ['hello_world']
});
};
Copy and paste examples
Init
Instantiate a new Pubnub instance. Only the subscribeKey
is mandatory. Also include publishKey
if you intend to publish from this instance, and the secretKey
if you wish to perform PAM administrative operations from this PhoneGap V4 instance.
It is not a best practice to include the When you init with |
Set restore as true to allow catch up on the front-end applications. |
Initializing the client
var pubnub = new PubNub({
subscribeKey: "mySubscribeKey",
publishKey: "myPublishKey",
ssl: true
})
Listeners
Adding Listeners
pubnub.addListener({
message: function(m) {
// handle message
var channelName = m.channel; // The channel for which the message belongs
var channelGroup = m.subscription; // The channel group or wildcard subscription match (if exists)
var pubTT = m.timetoken; // Publish timetoken
var msg = m.message; // The Payload
var publisher = m.publisher; //The Publisher
},
presence: function(p) {
// handle presence
var action = p.action; // Can be join, leave, state-change or timeout
var channelName = p.channel; // The channel for which the message belongs
var occupancy = p.occupancy; // No. of users connected with the channel
var state = p.state; // User State
var channelGroup = p.subscription; // The channel group or wildcard subscription match (if exists)
var publishTime = p.timestamp; // Publish timetoken
var timetoken = p.timetoken; // Current timetoken
var uuid = p.uuid; // UUIDs of users who are connected with the channel
},
signal: function(s) {
// handle signal
var channelName = s.channel; // The channel for which the signal belongs
var channelGroup = s.subscription; // The channel group or wildcard subscription match (if exists)
var pubTT = s.timetoken; // Publish timetoken
var msg = s.message; // The Payload
var publisher = s.publisher; //The Publisher
},
status: function(s) {
var affectedChannelGroups = s.affectedChannelGroups; // The channel groups affected in the operation, of type array.
var affectedChannels = s.affectedChannels; // The channels affected in the operation, of type array.
var category = s.category; //Returns PNConnectedCategory
var operation = s.operation; //Returns PNSubscribeOperation
var lastTimetoken = s.lastTimetoken; //The last timetoken used in the subscribe request, of type long.
var currentTimetoken = s.currentTimetoken; //The current timetoken fetched in the subscribe response, which is going to be used in the next request, of type long.
var subscribedChannels = s.subscribedChannels; //All the current subscribed channels, of type array.
}
});
Removing Listeners
var existingListener = {
message: function() {
}
}
pubnub.removeListener(existingListener)
listeners status events
Categories | Description |
---|---|
PNNetworkUpCategory | SDK detected that network is online. |
PNNetworkDownCategory | The SDK will announce this when connection is not available or this is not able to reach the PubNub Data Stream Network. |
PNNetworkIssuesCategory | A subscribe event experienced an exception when running. The SDK is not being to able reach the PubNub Data Stream Network because the machine or device are not connected to Internet or this has been lost, your ISP (Internet Service Provider) is having to troubles or perhaps or the SDK is behind of a proxy. |
PNReconnectedCategory | SDK was able to reconnect to pubnub. |
PNConnectedCategory | SDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed). |
PNAccessDeniedCategory | PAM permission failure. |
PNMalformedResponseCategory | JSON parsing crashed. |
PNBadRequestCategory | The server responded with bad response because the request is malformed. |
PNDecryptionErrorCategory | If using decryption strategies and the decryption fails. |
PNTimeoutCategory | Failure to establish connection due to timeout. |
PNRequestMessageCountExceedCategory | The SDK will announce this error if requestMessageCountThreshold is set and the number of messages arrived from (PubNub in memory cache messages) are greater than this. |
PNUnknownCategory | This status code is returned when the subscriber get’s a non 200 HTTP response code from the server. |
Time
time()
to verify the client connectivity to the origin:// assuming an initialized PubNub instance already exists
pubnub.time(function(status, response) {
if (status.error) {
// handle error if something went wrong based on the status object
} else {
console.log(response.timetoken);
}
})
Subscribe
Subscribe (listen on) a channel
pubnub.subscribe({
channels: ['my_channel'],
});
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method. |
Publish
pubnub.publish(
{
message: {
such: 'object'
},
channel: 'ch1',
sendByPost: false, // true to send via POST
storeInHistory: false, //override default storage options
meta: {
"cool": "meta"
} // publish extra meta with the request
},
function (status, response) {
// handle status, response
}
);
Here Now
here now
on the channel by UUID:Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys |
pubnub.hereNow(
{
channels: ["ch1"],
channelGroups : ["cg1"],
includeUUIDs: true,
includeState: true
},
function (status, response) {
// handle status, response
}
);
Presence
join
, leave
, and timeout
, by UUID. Setting the presence attribute to a callback will subscribe to presents events on my_channel
:Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys |
pubnub.subscribe({
channels: ['my_channel'],
withPresence: true
});
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method. |
History
Requires that the Storage and Playback add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys |
pubnub.history(
{
channel: 'history_channel',
count: 100, // how many items to fetch
stringifiedTimeToken: true, // false is the default
},
function (status, response) {
// handle status, response
}
);
Unsubscribe
Stop subscribing (listening) to a channel.
pubnub.unsubscribe({
channels: ['my_channel']
})
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method. |
Beta Version Available! | A beta release of the PubNub React framework, version 2.0 is now available. You can access it in the v2.0 branch of the |
Get Code: Source
Get Code: NPM
View Supported Platforms
Hello World
PubNub React is a wrapper of PubNub JavaScript SDK version 4 that adds a few of extra features to simplify the integration with React\React Native:
- Trigger Events:
getMessage
,getPresence
,getStatus
will make your life easier in the React' World. - Autoload: An easy and fast way to recovery the history messages of your channel.
You can still use the native PubNub JavaScript SDK if you feel this will be more suitable for your situation.
Differences in usage with native Javascript SDK
PubNub React is a wrapper of PubNub Javascript, which offers the same feature and in the same way like Javascript SDK makes, So if you have experience using Javascript SDK will be fast to learn the features included for React SDK in other way if you want to learn more about PubNub JavaScript features refer to native PubNub JavaScript SDK manual.
Differences between React and React Native
PubNub React works for both frameworks seamlessly the only difference will be how to you are going to implement all UI elements into the render()
if your app is done with React or React Native.
That's it, you are ready to start using PubNub React SDK.
Example
Hello World Example
Hello World Example using React
import React, { Component } from 'react';
import PubNubReact from 'pubnub-react';
export default class extends Component {
constructor(props) {
super(props);
this.pubnub = new PubNubReact({
publishKey: 'YOUR PUBLISH KEY',
subscribeKey: 'YOUR SUBSCRIBE KEY'
});
this.pubnub.init(this);
}
componentWillMount() {
this.pubnub.subscribe({
channels: ['channel1'],
withPresence: true
});
this.pubnub.getMessage('channel1', (msg) => {
console.log(msg);
});
this.pubnub.getStatus((st) => {
this.pubnub.publish({
message: 'hello world from react',
channel: 'channel1'
});
});
}
componentWillUnmount() {
this.pubnub.unsubscribe({
channels: ['channel1']
});
}
render() {
const messages = this.pubnub.getMessage('channel1');
return (
<div>
<ul>
{messages.map((m, index) => <li key={'message' + index}>{m.message}</li>)}
</ul>
</div>
);
}
}
Hello World Example using React Native
import React, { Component } from 'react';
import PubNubReact from 'pubnub-react';
export default class extends Component {
constructor(props) {
super(props);
this.pubnub = new PubNubReact({
publishKey: 'YOUR PUBLISH KEY',
subscribeKey: 'YOUR SUBSCRIBE KEY'
});
this.pubnub.init(this);
}
componentWillMount() {
this.pubnub.subscribe({
channels: ['channel1'],
withPresence: true
});
this.pubnub.getMessage('channel1', (msg) => {
console.log(msg);
});
this.pubnub.getStatus((st) => {
this.pubnub.publish({
message: 'hello world from react',
channel: 'channel1'
});
});
}
componentWillUnmount() {
this.pubnub.unsubscribe({
channels: ['channel1']
});
}
render() {
const messages = this.pubnub.getMessage('channel1');
return (
<View>
{messages.map((m, index) => <Text key={'message' + index}>{m.message}</Text>)}
</View>
);
}
}
How to use PubNubReact
In order to get the integration between your React's Component and PubNub, PubNubReact will be the way to get this without any kind of difficulty or extra job when you need render data in your UI.
|
import PubNubReact from 'pubnub-react';
constructor(props) {
super(props);
this.pubnub = new PubNubReact({
publishKey: 'YOUR PUBLISH KEY',
subscribeKey: 'YOUR SUBSCRIBE KEY'
});
this.pubnub.init(this);
}
componentWillMount() {
this.pubnub.subscribe({
channels: ['channel1']
});
this.pubnub.getMessage('channel1', (msg) => {
console.log(msg);
});
}
Events
Another key feature of this SDK is the ability to use trigger events, in addition to pass callbacks, getting all messages through states and inject them directly in your UI of your React\React Native Component in an easy and fast way.
Triggering and listening to events for the subscribe method
With Javascript SDK V4, you can find three different events (message, presence and status).
Triggering the events:
With the trigger events you can find a way to get real time apps with PubNub React very fast because it will be resolved the synchronization between the data received and the user interface through of updating of the states to invoke the render of the React's Component.
The trigger events are methods which encapsulate the events (message
, presence
and status
) with extra functionality to offer integration and get the process of development faster because will be resolved different scenarios which you can find when you are working with React\React Native.
To execute the trigger events you have to execute the init()
method first, in this way getMessage
, getPresence
and getStatus
will be available; these trigger events have the responsability to register a channel or a channelGroup in order to capture any real time message as soon as this is received and update the state then the Component renders automatically the user interface.
The getStatus
will only say to the Component that this has to render again if there is an update in the global state of the network.
To use getPresence
you will have to add the argument withPresence: true
when you are subscribing your channels.
this.pubnub.getStatus();
this.pubnub.getMessage('channel1');
this.pubnub.getMessage('channel2');
this.pubnub.getMessage('channelGroup1');
this.pubnub.getPresence('channel1');
this.pubnub.getPresence('channel2');
getMessage
Rendering real time messages from React
...
componentWillMount() {
this.pubnub.getMessage('channel1');
...
}
render() {
const messages = this.pubnub.getMessage('channel1');
return (
<div>
<ul>
{messages.map((m, index) => <li key={'message' + index}>{m.message}</li>)}
</ul>
</div>
);
}
...
Rendering real time messages from React Native
...
componentWillMount() {
this.pubnub.getMessage('channel1');
...
}
render() {
const messages = this.pubnub.getMessage('channel1');
return (
<View>
{messages.map((m) => <Text>{m.message}</Text>)}
</View>
);
}
...
In addition to be used to register channels or channelGroups you can also catch each message if you want to give it some kind of procedure to each message.
this.pubnub.getMessage('channel1', (msg) => {
console.log(msg);
});
When you are using getMessage
this going to keep the latest 100 messages received by default. But you can change this value when you attach the channel for first time with getMessage
.
this.pubnub.getMessage('channel1', (msg) => {
console.log(msg);
}, 20);
this.pubnub.getMessage('channel2', 30);
getPresence
Rendering presence object from react
...
componentWillMount() {
this.pubnub.getPresence('channel1', (presence) => {
console.log(presence);
});
...
}
render() {
const presence = this.pubnub.getPresence('channel1');
return (
<div>
<p>{presence.action}</p>
</div>
);
}
...
Rendering presence object from React Native
...
componentWillMount() {
this.pubnub.getPresence('channel1', (presence) => {
console.log(presence);
});
...
}
render() {
const presence = this.pubnub.getPresence('channel1');
return (
<View>
<Text>{presence.action}</Text>
</View>
);
}
...
Listening to the global status
Via the status listener, you can receive different events such as: when the network is online (PNNetworkUpCategory
), when the SDK is connected to a set of channels (PNConnectedCategory
), etc... See the list of events available in the API Reference.
...
componentWillMount() {
this.pubnub.getStatus((status) => {
console.log(status);
});
...
}
render() {
const status = this.pubnub.getStatus();
return (
<div>
<p>{status.category}</p>
</div>
);
}
...
Rendering the global status from React Native
...
componentWillMount() {
this.pubnub.getStatus((status) => {
console.log(status);
});
...
}
render() {
const status = this.pubnub.getStatus();
return (
<View>
<Text>{status.category}</Text>
</View>
);
}
...
Cleaning and Releasing
You can execute clean to remove all message cached in the state of the Component by the instance in running time without affecting the capture of new incoming messages for the trigger events.
this.pubnub.clean('myChannel1');
this.pubnub.clean('myGroup1');
You can execute release if you want to remove all message cached and stop of capturing new incoming messages for the trigger events.
this.pubnub.release('myChannel1');
this.pubnub.release('myGroup1');
this.pubnub.release(['myChannel1', 'myChannel2']);
Getting the history with autoload
At the moment that you are subscribing a channel you can pass the optional parameter autoload this value has to contain a value from 1 to 100 in order to retrieve the last messages published in the channel. When the getMessage
is called this going to retrieve the history. You can use a callback to know when the retrieving process has finished also this will take effect inside of state pn_message which will invoke a new render in your Component.
this.pubnub.subscribe({
channels: ['myChannel1'],
triggerEvents: true,
withPresence: true,
autoload: 100
});
let messages = this.pubnub.getMessage('myChannel1', () => {
console.log(messages);
});
Copy and paste examples
Init
Instantiate a new Pubnub instance. Only the subscribeKey
is mandatory. Also include publishKey
if you intend to publish from this instance, and the secretKey
if you wish to perform PAM administrative operations from this React V4 instance.
It is not a best practice to include the When you init with |
Set restore as true to allow catch up on the front-end applications. |
Initializing the client
this.pubnub = new PubNubReact({
publishKey: 'YOUR PUBLISH KEY',
subscribeKey: 'YOUR SUBSCRIBE KEY',
ssl: true
});
Listeners
Adding Listeners
this.pubnub.addListener({
status: (st) => {
if (st.category === "PNUnknownCategory") {
var newState = {new: 'error'};
pubnub.setState(
{
state: newState
},
function (status) {
console.log(st.errorData.message);
}
);
}
},
message: (message) => {
console.log(message);
}
});
this.pubnub.subscribe({
channels: ['my_channel']
});
Removing Listeners
var existingListener = {
message: function() {
}
}
this.pubnub.removeListener(existingListener)
listeners status events
Categories | Description |
---|---|
PNNetworkUpCategory | SDK detected that network is online. |
PNNetworkDownCategory | The SDK will announce this when connection is not available or this is not able to reach the PubNub Data Stream Network. |
PNNetworkIssuesCategory | A subscribe event experienced an exception when running. The SDK is not being to able reach the PubNub Data Stream Network because the machine or device are not connected to Internet or this has been lost, your ISP (Internet Service Provider) is having to troubles or perhaps or the SDK is behind of a proxy. |
PNReconnectedCategory | SDK was able to reconnect to pubnub. |
PNConnectedCategory | SDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed). |
PNAccessDeniedCategory | PAM permission failure. |
PNMalformedResponseCategory | JSON parsing crashed. |
PNBadRequestCategory | The server responded with bad response because the request is malformed. |
PNDecryptionErrorCategory | If using decryption strategies and the decryption fails. |
PNTimeoutCategory | Failure to establish connection due to timeout. |
PNRequestMessageCountExceedCategory | The SDK will announce this error if requestMessageCountThreshold is set and the number of messages arrived from (PubNub in memory cache messages) are greater than this. |
PNUnknownCategory | This status code is returned when the subscriber get’s a non 200 HTTP response code from the server. |
Time
time()
to verify the client connectivity to the origin:this.pubnub.time((status, response) => {
if (status.error) {
console.log(status.error);
} else {
console.log(response.timetoken);
}
});
Subscribe
Subscribe (listen on) a channel
this.pubnub.subscribe({
channels: ['my_channel'],
});
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method. |
Publish
this.pubnub.publish(
{
message: {
such: 'object'
},
channel: 'ch1',
sendByPost: false, // true to send via POST
storeInHistory: false, //override default storage options
meta: {
"cool": "meta"
} // publish extra meta with the request
},
(status, response) => {
// handle status, response
}
);
Here Now
here now
on the channel by UUID:Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys |
this.pubnub.hereNow(
{
channels: ["my_channel"],
channelGroups : ["my_channelGroup"],
includeUUIDs: true,
includeState: true
},
(status, response) => {
console.log(status);
console.log(response);
}
);
Presence
join
, leave
, and timeout
, by UUID. Setting the presence attribute to a callback will subscribe to presents events on my_channel
:Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys |
this.pubnub.subscribe({
channels: ['my_channel'],
withPresence: true
});
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method. |
History
Requires that the Storage and Playback add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys |
this.pubnub.history(
{
channel: 'my_channel',
count: 100, // 100 is the default
stringifiedTimeToken: true // false is the default
},
(status, response) => {
console.log(response);
}
);
Unsubscribe
Stop subscribing (listening) to a channel.
this.pubnub.unsubscribe({
channels : ['my_channel']
});
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method. |
Download a copy from:
Into your resources folder of your Titanium App.
View Supported Platforms
Hello World
PubNub Javascript SDK 4.27.1 has a distribution for Titanium which allows you to integrate PubNub to your mobile apps for iOS, Android and Mobile Web.
After downloading the source code and put this into the correct folder you can create an instance with simple lines of code in your app.js
file.
var PubNub = require('pubnub');
var pubnub = new PubNub({
subscribeKey: 'YOUR SUBSCRIBE KEY HERE',
publishKey: 'YOUR PUBLISH KEY HERE'
});
That's it, you are ready to start using PubNub JS SDK.
Example
Hello World Example
var PubNub = require('pubnub');
var pubnub = new PubNub({
subscribeKey: 'YOUR SUBSCRIBE KEY HERE',
publishKey: 'YOUR PUBLISH KEY HERE'
});
function publishSampleMessage() {
console.log("Since we're publishing on subscribe connectEvent, we're sure we'll receive the following publish.");
var publishConfig = {
channel : "hello_world",
message : {
title: "greeting",
description: "hello world!"
}
}
pubnub.publish(publishConfig, function(status, response) {
console.log(status, response);
})
}
pubnub.addListener({
status: function (st) {
if (st.category === "PNConnectedCategory") {
publishSampleMessage();
}
},
message: function (m) {
console.log(m.message.title);
console.log(m.message.description);
},
presence: function (ps) {
console.log(ps);
}
});
pubnub.subscribe({
channels: ['hello_world']
});
Copy and paste examples
Init
Instantiate a new Pubnub instance. Only the subscribeKey
is mandatory. Also include publishKey
if you intend to publish from this instance, and the secretKey
if you wish to perform PAM administrative operations from this Titanium V4 instance.
It is not a best practice to include the When you init with |
Set restore as true to allow catch up on the front-end applications. |
Initializing the client
var pubnub = new PubNub({
subscribeKey: 'YOUR SUBSCRIBE KEY HERE',
publishKey: 'YOUR PUBLISH KEY HERE',
ssl: true
});
Listeners
Adding Listeners
getMessage
, getPresence
, getStatus
methods. Remember add a listener before subscribing a channel.pubnub.addListener({
message: function(m) {
// handle message
var channelName = m.channel; // The channel for which the message belongs
var channelGroup = m.subscription; // The channel group or wildcard subscription match (if exists)
var pubTT = m.timetoken; // Publish timetoken
var msg = m.message; // The Payload
var publisher = m.publisher; //The Publisher
},
presence: function(p) {
// handle presence
var action = p.action; // Can be join, leave, state-change or timeout
var channelName = p.channel; // The channel for which the message belongs
var occupancy = p.occupancy; // No. of users connected with the channel
var state = p.state; // User State
var channelGroup = p.subscription; // The channel group or wildcard subscription match (if exists)
var publishTime = p.timestamp; // Publish timetoken
var timetoken = p.timetoken; // Current timetoken
var uuid = p.uuid; // UUIDs of users who are connected with the channel
},
signal: function(s) {
// handle signal
var channelName = s.channel; // The channel for which the signal belongs
var channelGroup = s.subscription; // The channel group or wildcard subscription match (if exists)
var pubTT = s.timetoken; // Publish timetoken
var msg = s.message; // The Payload
var publisher = s.publisher; //The Publisher
},
status: function(s) {
var affectedChannelGroups = s.affectedChannelGroups; // The channel groups affected in the operation, of type array.
var affectedChannels = s.affectedChannels; // The channels affected in the operation, of type array.
var category = s.category; //Returns PNConnectedCategory
var operation = s.operation; //Returns PNSubscribeOperation
var lastTimetoken = s.lastTimetoken; //The last timetoken used in the subscribe request, of type long.
var currentTimetoken = s.currentTimetoken; //The current timetoken fetched in the subscribe response, which is going to be used in the next request, of type long.
var subscribedChannels = s.subscribedChannels; //All the current subscribed channels, of type array.
}
});
Removing Listeners
var existingListener = {
message: function() {
}
}
pubnub.removeListener(existingListener);
listeners status events
Categories | Description |
---|---|
PNNetworkUpCategory | SDK detected that network is online. |
PNNetworkDownCategory | The SDK will announce this when connection is not available or this is not able to reach the PubNub Data Stream Network. |
PNNetworkIssuesCategory | A subscribe event experienced an exception when running. The SDK is not being to able reach the PubNub Data Stream Network because the machine or device are not connected to Internet or this has been lost, your ISP (Internet Service Provider) is having to troubles or perhaps or the SDK is behind of a proxy. |
PNReconnectedCategory | SDK was able to reconnect to pubnub. |
PNConnectedCategory | SDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed). |
PNAccessDeniedCategory | PAM permission failure. |
PNMalformedResponseCategory | JSON parsing crashed. |
PNBadRequestCategory | The server responded with bad response because the request is malformed. |
PNDecryptionErrorCategory | If using decryption strategies and the decryption fails. |
PNTimeoutCategory | Failure to establish connection due to timeout. |
PNRequestMessageCountExceedCategory | The SDK will announce this error if requestMessageCountThreshold is set and the number of messages arrived from (PubNub in memory cache messages) are greater than this. |
PNUnknownCategory | This status code is returned when the subscriber get’s a non 200 HTTP response code from the server. |
Time
time()
to verify the client connectivity to the origin:pubnub.time(function(status, response) {
if (status.error) {
console.log(status.error);
} else {
console.log(response.timetoken);
}
});
Subscribe
Subscribe (listen on) a channel
pubnub.subscribe({
channels: ['my_channel'],
withPresence: true
});
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method. |
Publish
pubnub.publish(
{
message: {
such: 'object'
},
channel: 'ch1',
sendByPost: false, // true to send via POST
storeInHistory: false, //override default storage options
meta: {
"cool": "meta"
} // publish extra meta with the request
},
function (status, response) {
// handle status, response
}
);
Here Now
here now
on the channel by UUID:Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys |
pubnub.hereNow(
{
channels: ["my_channel"],
channelGroups : ["my_channelGroup"],
includeUUIDs: true,
includeState: true
},
function (status, response) {
console.log(status);
console.log(response);
}
);
Presence
join
, leave
, and timeout
, by UUID. Setting the presence attribute to a callback will subscribe to presents events on my_channel
:Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys |
pubnub.addListener({
presence: function(m) {
console.log(m);
},
message: function(message) {
console.log(message)
}
});
pubnub.subscribe({
channels: ["my_channel"],
withPresence: true
});
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method. |
History
Requires that the Storage and Playback add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys |
pubnub.history(
{
channel: 'my_channel',
count: 100, // 100 is the default
stringifiedTimeToken: true // false is the default
},
function (status, response) {
console.log(response);
}
);
Unsubscribe
Stop subscribing (listening) to a channel.
pubnub.unsubscribe({
channels: ['my_channel']
})
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method. |
Get Code: Source
Get Code: NPM
View Supported Platforms
Hello World
PubNub
Vue is a wrapper of PubNub JavaScript SDK version 4 that adds a few of extra features to simplify the integration with Vue:
- Trigger Events:
$pnGetMessage
,$pnGetPresence
,$pnGetStatus
will make your life easier in the Vue' World. - Autoload: An easy and fast way to recovery the history messages of your channel.
You can still use the native PubNub JavaScript SDK if you feel this will be more suitable for your situation.
Differences in usage with native Javascript SDK
PubNub Vue is a wrapper of PubNub Javascript, which offers the same feature and in the same way as Javascript SDK makes, So if you have experience using Javascript SDK will be fast to learn the features included for Vue SDK in other way if you want to learn more about PubNub JavaScript features refer to native PubNub JavaScript SDK manual.
Example
Hello World Example
<template>
<div id="app">
<ol>
<li v-for="msg in ch1">{{msg.message}}</li>
</ol>
<button v-on:click="push">push</button>
</div>
</template>
<script>
export default {
name: 'app',
data() {
return {
ch1: this.$pnGetMessage('ch1'),
},
},
methods: {
push() {
this.$pnPublish({
channel: 'ch1',
message: Date.now()
},
(status, response) => console.log(status, response));
},
},
mounted() {
this.$pnSubscribe({
channels: ['ch1']
});
},
};
</script>
How to use PubNubVue
In order to get the integration between your Vue's Component and PubNub, PubNubVue will be the way to get this without any kind of difficulty or extra job when you need render data in your UI.
|
import Vue from 'vue';
import PubNubVue from 'pubnub-vue';
import App from './App';
Vue.use(PubNubVue, {
subscribeKey: 'YOUR SUBSCRIBE KEY HERE',
publishKey: 'YOUR PUBLISH KEY HERE'
});
new Vue({
el: '#app',
template: '<App/>',
components: {
App
},
});
Events
Another key feature of this SDK is the ability to use trigger events, in addition to pass callbacks, getting all messages through states and inject them directly in your UI of your Vue Component in an easy and fast way.
Triggering and listening to events for the subscribe method
With the trigger events you can find a way to get real time apps with PubNub Vue very fast, because it will be resolved the synchronization between the data received and the user interface through associating a channel to a reactive property to the root data object.
The trigger events are methods which encapsulate the events (message
, presence
and status
) from Javascript SDK v4 with extra functionality to offer integration and get the process of development faster because will be resolved different scenarios which you can find when you are working with Vue.
Triggering the events:
$pnGetMessage
Use $pnGetMessage
to associate a channel subscribed to a reactive property and start to display messages as soon as these are received.
Parameter | Type | Required | Defaults | Description |
---|---|---|---|---|
channel | String | Yes | Channel which will be listened. | |
callback | Function | Optional | Function which will be invoked as soon as received a new real time message. | |
keepMessage | Number | Optional | Number of messages which are kept and rendered . | |
instanceName | String | Optional | default | Instance to use into the component. |
<template>
<div id="app">
<ol>
<li v-for="msg in ch1">{{ msg.message }}</li>
</ol>
</div>
</template>
<script>
export default {
name: 'app',
data() {
return {
ch1: this.$pnGetMessage('ch1'),
},
},
mounted() {
this.$pnSubscribe({
channels: ['ch1', 'ch2']
});
},
};
</script>
$pnGetMessage
will receive a second parameter which is a callback function that is going to be invoked as soon as received a new real time message. This will allow to apply transformation or manipulate of somehow to each message or implement a custom mechanism to render these.
<template>
<div id="app">
<ol>
<li v-for="msg in ch1">{{ msg.message }}</li>
</ol>
</div>
</template>
<script>
export default {
name: 'app',
data() {
return {
ch1: this.$pnGetMessage('ch1', this.receptor),
},
},
methods: {
receptor(msg) {
msg.message = `sent - ${msg.message}`;
},
},
mounted() {
this.$pnSubscribe({
channels: ['ch1', 'ch2']
});
},
};
</script>
When you are using $pnGetMessage
this going to keep the latest 100 messages received by default. But you can change this value when you attach the channel with $pnGetMessage
.
<template>
<div id="app">
<ol>
<li v-for="msg in ch1">{{ msg.message }}</li>
</ol>
</div>
</template>
<script>
export default {
name: 'app',
data() {
return {
ch1: this.$pnGetMessage('ch1', null, 10),
},
},
methods: {
receptor(msg) {
msg.message = `sent - ${msg.message}`;
},
},
mounted() {
this.$pnSubscribe({
channels: ['ch1', 'ch2']
});
},
};
</script>
$pnGetPresence
To use $pnGetPresence
you will have to add the argument withPresence: true
when you are subscribing your channels.
Parameter | Type | Required | Defaults | Description |
---|---|---|---|---|
channel | String | Yes | Channel which will be listened. | |
callback | Function | Optional | Function which will be invoked as soon as a new presence message is invoked . | |
instanceName | String | Optional | default | Instance to use into the component. |
<template>
<div id="app">
<span>occupancy: {{ occupancy }}</span>
</div>
</template>
<script>
export default {
name: 'app',
data() {
return {
occupancy: 0,
};
},
methods: {
presence(ps) {
this.occupancy = ps.occupancy;
console.log(ps);
},
},
mounted() {
this.$pnSubscribe({
channels: ['ch1'],
withPresence: true
});
this.$pnGetPresence('ch1', this.presence);
},
};
</script>
Listening to the global status
The $pnGetStatus
which is wrapper of the status listener, you can receive different events such as: when the network is online (PNNetworkUpCategory
), when the SDK is connected to a set of channels (PNConnectedCategory
), etc... See the list of events available in the API Reference.
Parameter | Type | Required | Defaults | Description |
---|---|---|---|---|
callback | Function | Optional | Function which will be invoked as soon as a new change in the network. | |
instanceName | String | Optional | default | Instance to use into the component. |
<template>
<div id="app">
<span>category: {{ category }}</span>
</div>
</template>
<script>
export default {
name: 'app',
data() {
return {
category: '',
};
},
methods: {
status(st) {
console.log(st);
this.category = st.category;
},
},
mounted() {
this.$pnSubscribe({
channels: ['ch1']
});
this.$pnGetStatus(this.status);
},
};
</script>
Publishing
Parameter | Type | Required | Defaults | Description |
---|---|---|---|---|
args | Object | Yes | A hash of arguments to make the unsubscription. | |
callback | Function | Optional | Function which will be invoked after publishing the message. | |
instanceName | String | Optional | default | Instance to use into the component. |
this.$pnPublish(
{
channel: 'ch1',
message: Date.now()
},
(status, response) => console.log(status, response)
);
Cleaning and Releasing
You can execute clean to remove all message cached in the state of the Component by the instance in running time without affecting the capture of new incoming messages for the trigger events.
Parameter | Type | Required | Defaults | Description |
---|---|---|---|---|
channel | String | Yes | Channel which will be cleaned. | |
instanceName | String | Optional | default | Instance to use into the component. |
this.$pnClean('ch1');
You can execute release if you want to remove all message cached and stop of capturing new incoming messages for the trigger events.
Parameter | Type | Required | Defaults | Description |
---|---|---|---|---|
channel | String | Yes | Channel which will be released. | |
instanceName | String | Optional | default | Instance to use into the component. |
this.$pnRelease('ch1');
Getting the history with autoload
At the moment that you are subscribing a channel you can pass the optional parameter autoload
this value has to contain a value from 1 to 100 in order to retrieve the last messages published in the channel. When the $pnGetMessage
is called this going to retrieve the history. You can use a callback to know when the retrieving process has finished.
Parameter | Type | Required | Defaults | Description |
---|---|---|---|---|
args | Object | Yes | A hash of arguments to make the subscription. | |
instanceName | String | Optional | default | Instance to use into the component. |
this.$pnSubscribe({
channels: ['ch1'],
autoload: 100
});
Unsubscribing
Parameter | Type | Required | Defaults | Description |
---|---|---|---|---|
args | Object | Yes | A hash of arguments to make the unsubscription. | |
instanceName | String | Optional | default | Instance to use into the component. |
this.$pnUnsubscribe({
channels: ['ch1']
});
Getting the original instance
The functions described above are the most used but if you need to use some of the rest which are not found like extended functions in Vue, you can continue to access to them through the original instance which is going to offer all capabilities that you can find using Javascript SDK.
const instance = this.$pnGetInstance();
or
import PubNubVue from 'pubnub-vue';
const instance = PubNubVue.getInstance();
Getting a new instance
Use the hook created to initialize new instances. |
The $pnGetInstance
method will return the main instance which be created by default but if we need to create an additional instance, we can pass as a parameter the name of a new one instance and with this same name, you will have the capability of retrieving from other component inside of our application.
<template>
<div id="app">
<ol>
<li v-for="msg in ch1">{{ msg.message }}</li>
</ol>
</div>
</template>
<script>
export default {
name: 'app',
data() {
return {
ch1: this.$pnGetMessage('ch1', null, 10, 'instance2'),
};
},
mounted() {
this.$pnSubscribe(
{
channels: ['ch1']
},
'instance2'
);
},
created() {
this.$pnGetInstance('instance2');
},
};
</script>
The previous example will listen to the channel ch1
without using callback function and it is going to render only the last 10 message received with the usage of the instance instance2
.
this.$pnGetMessage(
'ch1',
null,
10,
'instance2'
)
By default all extended methods use the instance by default if you need to use some of them with other instance you will have to set as parameter the name of the instance to use when you invoke the method according to list of parameter that receives.
const instance2 = PubNubVue.getInstance('instance2');
or
const instance = this.$pnGetInstance('instance2');
Copy and paste examples
For the next examples we will have to use the original instance in order to access to do not extended methods. |
Init
subscribeKey
is mandatory but if you want to publish from this instance, you have to set the secretKey
in addition if you wish to perform PAM administrative operations.It is not the best practice to include secretKey in client-side code for security reason. |
Set restore as true to allow catch up on the front-end applications. |
Initializing the client
import Vue from 'vue';
import PubNubVue from 'pubnub-vue';
Vue.use(PubNubVue, {
subscribeKey: "mySubscribeKey",
publishKey: "myPublishKey",
ssl: true
});
Listeners
Adding Listeners
$pnGetMessage
, $pnGetPresence
, $pnGetStatus
methods. Remember add a listener before subscribing a channel.import PubNubVue from 'pubnub-vue';
const pubnub = PubNubVue.getInstance();
pubnub.addListener({
message: function(m) {
// handle message
var channelName = m.channel; // The channel for which the message belongs
var channelGroup = m.subscription; // The channel group or wildcard subscription match (if exists)
var pubTT = m.timetoken; // Publish timetoken
var msg = m.message; // The Payload
var publisher = m.publisher; //The Publisher
},
presence: function(p) {
// handle presence
var action = p.action; // Can be join, leave, state-change or timeout
var channelName = p.channel; // The channel for which the message belongs
var occupancy = p.occupancy; // No. of users connected with the channel
var state = p.state; // User State
var channelGroup = p.subscription; // The channel group or wildcard subscription match (if exists)
var publishTime = p.timestamp; // Publish timetoken
var timetoken = p.timetoken; // Current timetoken
var uuid = p.uuid; // UUIDs of users who are connected with the channel
},
status: function(s) {
var affectedChannelGroups = s.affectedChannelGroups;
var affectedChannels = s.affectedChannels;
var category = s.category;
var operation = s.operation;
}
});
Removing Listeners
import PubNubVue from 'pubnub-vue';
const pubnub = PubNubVue.getInstance();
const existingListener = {
message: function() {
}
}
pubnub.removeListener(existingListener);
listeners status events
Categories | Description |
---|---|
PNNetworkUpCategory | SDK detected that network is online. |
PNNetworkDownCategory | The SDK will announce this when connection is not available or this is not able to reach the PubNub Data Stream Network. |
PNNetworkIssuesCategory | A subscribe event experienced an exception when running. The SDK is not being to able reach the PubNub Data Stream Network because the machine or device are not connected to Internet or this has been lost, your ISP (Internet Service Provider) is having to troubles or perhaps or the SDK is behind of a proxy. |
PNReconnectedCategory | SDK was able to reconnect to pubnub. |
PNConnectedCategory | SDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed). |
PNAccessDeniedCategory | PAM permission failure. |
PNMalformedResponseCategory | JSON parsing crashed. |
PNBadRequestCategory | The server responded with bad response because the request is malformed. |
PNDecryptionErrorCategory | If using decryption strategies and the decryption fails. |
PNTimeoutCategory | Failure to establish connection due to timeout. |
PNRequestMessageCountExceedCategory | The SDK will announce this error if requestMessageCountThreshold is set and the number of messages arrived from (PubNub in memory cache messages) are greater than this. |
PNUnknownCategory | This status code is returned when the subscriber get’s a non 200 HTTP response code from the server. |
Time
time()
to verify the client connection to the origin:import PubNubVue from 'pubnub-vue';
const pubnub = PubNubVue.getInstance();
pubnub.time(function(status, response) {
if (status.error) {
// handle error if something went wrong based on the status object
} else {
console.log(response.timetoken);
}
});
Subscribe
Subscribe (listen on) a channel
import PubNubVue from 'pubnub-vue';
const pubnub = PubNubVue.getInstance();
pubnub.subscribe({
channels: ['my_channel']
});
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method. |
Publish
const pubnub = PubNubVue.getInstance();
pubnub.publish(
{
message: {
such: 'object'
},
channel: 'ch1',
sendByPost: false, // true to send via POST
storeInHistory: false, //override default storage options
meta: {
"cool": "meta"
} // publish extra meta with the request
},
function(status, response) {
// handle status, response
}
);
Here Now
here now
on the channel by UUID:Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys |
import PubNubVue from 'pubnub-vue';
const pubnub = PubNubVue.getInstance();
pubnub.hereNow(
{
channels: ["ch1"],
channelGroups : ["cg1"],
includeUUIDs: true,
includeState: true
},
function(status, response) {
// handle status, response
}
);
Presence
join
, leave
, and timeout
, by UUID. Setting the presence attribute to a callback will subscribe to presents events on my_channel
:Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys |
import PubNubVue from 'pubnub-vue';
const pubnub = PubNubVue.getInstance();
pubnub.subscribe({
channels: ['my_channel'],
withPresence: true
});
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method. |
History
Requires that the Storage and Playback add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys |
import PubNubVue from 'pubnub-vue';
const pubnub = PubNubVue.getInstance();
pubnub.history(
{
channel: 'history_channel',
count: 100, // how many items to fetch
stringifiedTimeToken: true, // false is the default
},
function(status, response) {
// handle status, response
}
);
Unsubscribe
Stop subscribing (listening) to a channel.
import PubNubVue from 'pubnub-vue';
const pubnub = PubNubVue.getInstance();
pubnub.unsubscribe({
channels: ['my_channel']
});
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method. |