IN THIS ARTICLE
Good News! We’ve launched an all new Chat Resource Center.
We recommend checking out our new Chat Resource Center, which includes overviews, tutorials, and design patterns for building and deploying mobile and web chat.
In this tutorial, we’ll move on to talking about how to spawn an infinite amount of new channels to create chatroom(s) on demand. So far, all of our communication has happened over a couple static channels, so now we’re going to take that a step further with how to create chatroom(s) on demand.
Create Chatroom(s) and Spawning Infinite Channels on Demand
The ability to create new channels on demand is important for things like user-to-user private chat or spawning new multiplayer game servers. More broadly speaking, this tutorial applies to any situation where you need to create any number of channels.
We’ve now covered both building a multiplayer game lobby with a chatroom and the different ways we can use matchmaking to connect two different users. Here’s what we’ve covered so far:
- Part One: Series Overview and Building a Multiplayer Game Lobby
- Part Two: Adding Users and Usernames
- Part Three: Getting a List of Online Users
- Part Four: Random Matchmaking of Users
- Part Five: Skill-based Matchmaking of Users
- Part Six: Matchmaking Algorithm: Enabling Users to Challenge Other Players
- Part Seven: Create Chatrooms and Multiple Channels On Demand Tutorial
- Part Eight: Preparing for Private Chatrooms and Refactoring via Private Channels
- Part Nine: Creating Private Chat Requests with Popup Alerts
- Part Ten: JavaScript Private Chat API with Access Control
This blog post is Part Seven of PubNub Developer Evangelist Ian Jennings‘s series on creating a multiplayer game with JavaScript.
Closures
Infinite is a big number, so we’ll need to employ some advanced Javascript concepts to keep our code in order. In this demo we’re going to harness the power of Javascript closures and object oriented programming to create an infinite number of chatrooms.
You’ll first need to sign up for a PubNub account. Once you sign up, you can get your unique PubNub keys in the PubNub Developer Portal. Once you have, clone the GitHub repository, and enter your unique PubNub keys on the PubNub initialization, for example:
Now, let’s take a look at an example of a Javascript closure.
The setTimeout(x, y)
function waits y
milliseconds to fire function x
.
The output would look like:
The function setTimeout()
waits an entire second before calling handle()
. handle()
is still able to access the values of name
and timeout
even after the function has returned because it is in a closure.
An inner function always has access to the vars and parameters of its outer function, even after the outer function has returned. Read more: http://javascript.crockford.com/private.html
Closures preserve the environment so that even a full second later, setTimeout()
still has access to the variables defined within the scope of the parent function.
The function defined in the closure ‘remembers’ the environment in which it was created. Read more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures
Closures are notoriously a difficult concept to grasp. I highly recommend reading the detailed explanation of closures provided by Mozilla. There are also some helpful explanations on Stack Overflow.
Chatroom Refactor
Let’s take a look at how we can use closures to dynamically create chatroom(s) on demand. Unlike previous chapters, we won’t be building off our previous code examples. Instead, we’re going to refactor the “Chatroom” example from the first chapter. Instead of defining everything globally, we store all of our variables within the Chatroom()
object and make sure all variables are relative to that object rather than the global scope. Notice the similarities between Chatroom()
and Alarm()
from earlier.
We’ve covered most of this code before. The largest change is that it is now encapsulated within the Chatroom()
function.
Infinite Chatrooms
Now, we’ll add an event the #spawn-chatroom
click handler. When the button is clicked, we’ll call Chatroom();
to create chatrooms on demand with a new id and template.
Keeping Things Relative
Like the setTimeout()
in our Alarm()
example, even though the Chatroom()
function returns immediately pubnub.subscribe()
appends the message to the correct chatroom.
The message can come minutes or hours later. PubNub can even disconnect and reconnect. The environment will always know what specific .chat-output
to append PubNub messages to because the closure has preserved the relationship between the subscribe call and the object that initiated it.
Create Chatrooms and Spawn Multiple Channels Demo
Check out the full demo embedded below, or check out the create chatroom demo on CodePen.
See the Pen Memewarz – Chatroom Spawn #2 by Ian Jennings (@ianjennings) on CodePen.0
Overload
But what about all the subscription calls? Won’t PubNub get overloaded? Is there a limit to the number of channels I can subscribe to? Will this clog the tubes?
Thanks to PubNub multiplexing, you can subscribe to as many channels as you want without worrying about latency. Channels are an abstract concept and don’t create any additional connections.
Instead, the messages are bundled together and distributed accordingly. If you look at the actual subscribe network headers, you can see every channel represented in the same single request.
Networking in an object oriented way is exciting. This pattern is extremely empowering and you can use it to build almost anything in a organized and scalable fashion.
We’ll be using it in the future to create private chat from user to user and spawn game servers on demand.