SlideShare une entreprise Scribd logo
1  sur  10
PubNub Messenger: !
Room Management,
History and
Presence!
by Dan Ristic
This is the second of a three-part series explaining how to build a multi-user messaging application
using jQuery Mobile and PubNub. You can read the series overview here.

Now that we have built a basic chat room it is time to give our users some more functionality. In part
two of this series we will expand on part one by managing multiple rooms, showing users a history of
previous messages, and showing what users are in the room.

As a quick note, from here on out I will be showing fragments of the final source code that will not
work by copy and pasting. This is in order to focus on the learning points and keep the code
examples shorter. If you would like the fully working version please check out the final version of this
demo at https://github.com/dristic/pub-messenger.
Joining Multiple Rooms

Our app would be complete if every person wanted to talk to everyone else using the app at the same time in one
giant chat room. Unfortunately for us people always want more features. The first feature we will add is the ability to
join different chat rooms and keep a list of the ones that the user has joined.

We will now have two pages to our app and use jQuery Mobile’s page navigation feature to switch between them. This
will keep everything running in a single page meaning we can build on top of all the previous part’s code. The UI for
this page is pretty simple. It includes a list view, an input box, and a button which are all native jQuery Mobile
components.
<!-- Chat List Page -->	
<div data-role="page" id="chatListPage" data-theme="c" class="type-chat-list">	
<div data-role="header">	
<h1>Current Chats</h1>	
</div>	
	
<div data-role="content">	
<input type="text" name="name" id="chatRoomName" placeholder="Chat Room Name" />	
<a href="#" id="newChatButton" data-role="button">Join New Chat</a>	
	
<br />	
	
<ul data-role="listview" data-split-icon="delete" data-split-theme="c" id="chatList">	
<!-- <li><span class="username">User123:</span>This is my message.</li> -->	
</ul>	
</div>	
</div>
Now we use some simple JavaScript to display a list of subscriptions when the user navigates to this page. The list is
stored as an array of strings globally throughout the application. In the final version I decided to use localStorage to
keep the state of this array between application uses. This even works on mobile devices for some quick and easy
device side storage and still keeps our app cross platform.
var chatChannel = '',	
chatRoomName = $('#chatRoomName'),	
charListEl = $('#chatList'),	
subscriptions = [],	
pages = {	
chatList: $("#chatListPage"),	
chat: $("#chatPage")	
};	
function onChatListOpen () {	
chatListEl.empty();	
for(var i = 0; i < subscriptions.length; i++) {	
var chatName = subscriptions[i],	
chatEl = $("<li><a href='#chatPage' data-channel-name='" + chatName + "'>" 	
+ chatName 	
+ "</a><a href='#delete' data-rel='dialog' data-channel-name='" + chatName + "'></a></li>");	
chatListEl.append(chatEl);	
chatListEl.listview('refresh');	
}	
newChatButton.off('click');	
newChatButton.click(function (event) {	
if(chatRoomName.val() !== '') {	
chatChannel = chatRoomName.val();	
	
$.mobile.changePage(pages.chat);	
}	
});	
};
The other HTML5 goodness I am using is the data- attributes on each link to keep the channel name. This allows me
to pass data between my views without doing too much work. I can simply navigate to the chat room view and
check for any data- attributes coming from the link source.

The final few things here is creating a new chat button that accepts a room name from the input box and navigates
to the chat room view. Also do not forget to create a back button on the chat room view as well as handle coming
from the link versus the new room button. I also make sure to unsubscribe from the channel when going back to the
chat room list view.
History

Another great feature we can add is seeing a history of
recent messages when the user enters a chat room.
PubNub has an additional feature for history that allows
you to get a number of previous messages sent in any
channel. The call easily integrates with our current app
by looping through the list of previous messages and
then sending them through our message handler as if we
just got a message from subscribe.
pubnub.history({	
channel: chatChannel,	
limit: 100	
}, function (messages) {	
messages = messages[0];	
messages = messages || [];	
	
for(var i = 0; i < messages.length; i++) {	
handleMessage(messages[i], false);	
}	
	
$(document).scrollTop($(document).height());	
});
Presence

The final feature we want to add is a user list for seeing who is
currently chatting in the room we are in. Our strategy for this is going
to be using a combination of unique ids and presence from our
PubNub API to handle all the back end work for us.

The idea for the user interface would be a two column layout that hides
the user list on mobile phones. This came from the jQuery Mobile
documentation site which has a left column navigation on larger
screens and a collapsed version on smaller ones. This will also stay in
line with the idea of being cross platform and being able to build to
multiple devices at once. I used parts of the extra bit of css found
here.

http://jquerymobile.com/demos/1.2.0/docs/_assets/css/jqm-docs.css
on the jQuery mobile documentation that allows for a content-primary
and content-secondary areas which handle most of this for us. From
there it was a lot of tweaking to get the final version that exists in the
Github repository. Here is the updated html for the chat page:
<div data-role="page" id="chatPage" data-theme="c" class="type-interior">	
	
<div data-role="content">	
<div class="content-primary">	
<div data-role="header" data-position="fixed" data-tap-toggle="false">	
<h1>Pub Messenger</h1>	
</div><!-- /header -->	
	
<div data-role="content">	
<ul data-role="listview" id="messageList">	
<!-- <li><span class="username">User123:</span>This is my message.</li> -->	
</ul>	
</div>	
	
<div data-role="footer" data-theme="c">	
<textarea id="messageContent"></textarea>	
<div class="ui-grid-a">	
<div class="ui-block-a"><a href="#" id="sendMessageButton" data-role="button">Send Message</a></div>	
<div class="ui-block-b"><a href="#" id="backButton" data-rel="back" data-role="button">Chat Rooms</a></div>	
</div>	
</div>	
</div>	
	
<div class="content-secondary">	
<ul data-role="listview" id="userList" data-theme="c">	
	
</ul>	
</div>	
</div><!-- /content -->	
	
</div><!-- /page -->	
Presence (cont.)
Surprisingly the hardest part was actually getting the user interface to be responsive. Actually wiring this up with
JavaScript was delightfully simple. First off I created a home page with an input box which allows the user to input a
chat room name. I then capture this and add send this as the UUID with the PubNub connection like so:
PUBNUB.init({	
publish_key: 'demo',	
subscribe_key: 'demo',	
uuid: username // This is where the entered username goes.	
});
Now we add a presence listening function in the subscribe call. This will get fired every time a user in the same
channel does an action such as joining the channel or leaving. Since all we care about for now is joining or leaving we
check and see what the message action is and either remove or add the username from our user list UI. PubNub
takes care of the rest!














After all those juicy features we now come to the end of part two. We gave our demanding users some more features
including joining different chat rooms, seeing chat history, and seeing what other users are currently chatting. I will
wrap this up in Part 3 where I will explain how to package everything up with PhoneGap, tying up the responsive UI,
and future thinking on scalability and performance.
var users = [],	
userList = $("#userList");	
	
pubnub.subscribe({	
channel: chatChannel,	
message: handleMessage, // Our global handle message function	
presence: function(message, env, channel) { // This gets called on user leave / enter	
if (message.action == "join") {	
users.push(message.uuid);	
userList.append("<li data-username='" + message.uuid + "'>" + message.uuid + "</li>");	
} else if (message.action == "leave") {	
users.splice(users.indexOf(message.uuid), 1);	
userList.find('[data-username="' + message.uuid + '"]').remove();	
}	
	
userList.listview('refresh');	
}	
});

Contenu connexe

Dernier

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 

Dernier (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 

En vedette

Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 

En vedette (20)

Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 

PubNub Messenger: Room Management, History, and Presence (Part 2 of 3)

  • 1. PubNub Messenger: ! Room Management, History and Presence! by Dan Ristic
  • 2. This is the second of a three-part series explaining how to build a multi-user messaging application using jQuery Mobile and PubNub. You can read the series overview here. Now that we have built a basic chat room it is time to give our users some more functionality. In part two of this series we will expand on part one by managing multiple rooms, showing users a history of previous messages, and showing what users are in the room. As a quick note, from here on out I will be showing fragments of the final source code that will not work by copy and pasting. This is in order to focus on the learning points and keep the code examples shorter. If you would like the fully working version please check out the final version of this demo at https://github.com/dristic/pub-messenger.
  • 3. Joining Multiple Rooms Our app would be complete if every person wanted to talk to everyone else using the app at the same time in one giant chat room. Unfortunately for us people always want more features. The first feature we will add is the ability to join different chat rooms and keep a list of the ones that the user has joined. We will now have two pages to our app and use jQuery Mobile’s page navigation feature to switch between them. This will keep everything running in a single page meaning we can build on top of all the previous part’s code. The UI for this page is pretty simple. It includes a list view, an input box, and a button which are all native jQuery Mobile components. <!-- Chat List Page --> <div data-role="page" id="chatListPage" data-theme="c" class="type-chat-list"> <div data-role="header"> <h1>Current Chats</h1> </div> <div data-role="content"> <input type="text" name="name" id="chatRoomName" placeholder="Chat Room Name" /> <a href="#" id="newChatButton" data-role="button">Join New Chat</a> <br /> <ul data-role="listview" data-split-icon="delete" data-split-theme="c" id="chatList"> <!-- <li><span class="username">User123:</span>This is my message.</li> --> </ul> </div> </div>
  • 4. Now we use some simple JavaScript to display a list of subscriptions when the user navigates to this page. The list is stored as an array of strings globally throughout the application. In the final version I decided to use localStorage to keep the state of this array between application uses. This even works on mobile devices for some quick and easy device side storage and still keeps our app cross platform. var chatChannel = '', chatRoomName = $('#chatRoomName'), charListEl = $('#chatList'), subscriptions = [], pages = { chatList: $("#chatListPage"), chat: $("#chatPage") }; function onChatListOpen () { chatListEl.empty(); for(var i = 0; i < subscriptions.length; i++) { var chatName = subscriptions[i], chatEl = $("<li><a href='#chatPage' data-channel-name='" + chatName + "'>" + chatName + "</a><a href='#delete' data-rel='dialog' data-channel-name='" + chatName + "'></a></li>"); chatListEl.append(chatEl); chatListEl.listview('refresh'); } newChatButton.off('click'); newChatButton.click(function (event) { if(chatRoomName.val() !== '') { chatChannel = chatRoomName.val(); $.mobile.changePage(pages.chat); } }); };
  • 5. The other HTML5 goodness I am using is the data- attributes on each link to keep the channel name. This allows me to pass data between my views without doing too much work. I can simply navigate to the chat room view and check for any data- attributes coming from the link source. The final few things here is creating a new chat button that accepts a room name from the input box and navigates to the chat room view. Also do not forget to create a back button on the chat room view as well as handle coming from the link versus the new room button. I also make sure to unsubscribe from the channel when going back to the chat room list view.
  • 6. History Another great feature we can add is seeing a history of recent messages when the user enters a chat room. PubNub has an additional feature for history that allows you to get a number of previous messages sent in any channel. The call easily integrates with our current app by looping through the list of previous messages and then sending them through our message handler as if we just got a message from subscribe. pubnub.history({ channel: chatChannel, limit: 100 }, function (messages) { messages = messages[0]; messages = messages || []; for(var i = 0; i < messages.length; i++) { handleMessage(messages[i], false); } $(document).scrollTop($(document).height()); });
  • 7. Presence The final feature we want to add is a user list for seeing who is currently chatting in the room we are in. Our strategy for this is going to be using a combination of unique ids and presence from our PubNub API to handle all the back end work for us. The idea for the user interface would be a two column layout that hides the user list on mobile phones. This came from the jQuery Mobile documentation site which has a left column navigation on larger screens and a collapsed version on smaller ones. This will also stay in line with the idea of being cross platform and being able to build to multiple devices at once. I used parts of the extra bit of css found here. http://jquerymobile.com/demos/1.2.0/docs/_assets/css/jqm-docs.css on the jQuery mobile documentation that allows for a content-primary and content-secondary areas which handle most of this for us. From there it was a lot of tweaking to get the final version that exists in the Github repository. Here is the updated html for the chat page:
  • 8. <div data-role="page" id="chatPage" data-theme="c" class="type-interior"> <div data-role="content"> <div class="content-primary"> <div data-role="header" data-position="fixed" data-tap-toggle="false"> <h1>Pub Messenger</h1> </div><!-- /header --> <div data-role="content"> <ul data-role="listview" id="messageList"> <!-- <li><span class="username">User123:</span>This is my message.</li> --> </ul> </div> <div data-role="footer" data-theme="c"> <textarea id="messageContent"></textarea> <div class="ui-grid-a"> <div class="ui-block-a"><a href="#" id="sendMessageButton" data-role="button">Send Message</a></div> <div class="ui-block-b"><a href="#" id="backButton" data-rel="back" data-role="button">Chat Rooms</a></div> </div> </div> </div> <div class="content-secondary"> <ul data-role="listview" id="userList" data-theme="c"> </ul> </div> </div><!-- /content --> </div><!-- /page --> Presence (cont.)
  • 9. Surprisingly the hardest part was actually getting the user interface to be responsive. Actually wiring this up with JavaScript was delightfully simple. First off I created a home page with an input box which allows the user to input a chat room name. I then capture this and add send this as the UUID with the PubNub connection like so: PUBNUB.init({ publish_key: 'demo', subscribe_key: 'demo', uuid: username // This is where the entered username goes. });
  • 10. Now we add a presence listening function in the subscribe call. This will get fired every time a user in the same channel does an action such as joining the channel or leaving. Since all we care about for now is joining or leaving we check and see what the message action is and either remove or add the username from our user list UI. PubNub takes care of the rest! After all those juicy features we now come to the end of part two. We gave our demanding users some more features including joining different chat rooms, seeing chat history, and seeing what other users are currently chatting. I will wrap this up in Part 3 where I will explain how to package everything up with PhoneGap, tying up the responsive UI, and future thinking on scalability and performance. var users = [], userList = $("#userList"); pubnub.subscribe({ channel: chatChannel, message: handleMessage, // Our global handle message function presence: function(message, env, channel) { // This gets called on user leave / enter if (message.action == "join") { users.push(message.uuid); userList.append("<li data-username='" + message.uuid + "'>" + message.uuid + "</li>"); } else if (message.action == "leave") { users.splice(users.indexOf(message.uuid), 1); userList.find('[data-username="' + message.uuid + '"]').remove(); } userList.listview('refresh'); } });