Thursday, 20 April, 2017 UTC


Summary

This blog post was written under the Pusher Guest Writer program.
Dashboards are a common feature of modern day applications. Users like to see an overview of their performance, on a single page, and a really great way to improve that experience is to make the information shown to them be dynamic, or realtime!
Counters are one of the prominent components of user dashboards, and in this tutorial, I will be showing you how to create a realtime counter, using the broadcasting prowess of Pusher and the simplicity of plain JavaScript. We will build a simple vote counter to count the number of votes an item gets, in real time.
To follow along, you will need a working knowledge of JavaScript. I will also be using basic ES6 syntax.
First, we will set up Pusher, then create our Node.js Application, and finally we will create our view and listen for changes to the number of votes for an item.
Setting up Pusher
Pusher’s APIs make it very easy to add realtime functionality to your applications. You should signup to a free account (if you haven’t already done so), create an app, and copy out the app credentials (App ID, Key and Secret) from the “App Keys” section, as we will be needing these for our app interaction with Pusher.
Creating Our App
We will be building our backend on Node.js, make sure you have it installed, then you can initialise the new app with:
npm init -y
Tip: The -y or --yes flag helps to create a package.json file with default values.
Next, we will install Express and Pusher and save as dependencies in our package.json file, via npm:
npm install -S express pusher
Now, we can create the files needed for our application:
./server.js
./index.html
The server.js file will contain our server-side code, and index.html will contain our view and event listener script.

Building the Backend

In our server.js file, first we will initialise Express, require the path module and require Pusher:
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname)));
const Pusher = require('pusher');
Next, we will Initialise Pusher with our app credentials, gotten from the Pusher dashboard:
const pusher = new Pusher({
  appId: 'YOUR_APP_ID',
  key: 'YOUR_APP_KEY',
  secret: 'YOUR_APP_SECRET',
  cluster: 'eu',
  encrypted: true
});
Note: If you created your app in a different cluster to the default us-east-1, you must configure the cluster option. It is optional if you chose the default option. encrypted is also optional.
Now we can start defining our app’s routes and responses.
When a user visits the homepage, we want to serve our index.html file, so we define a route for /:
app.get('/', (req,res) => {  
  res.sendFile('index.html', {root: __dirname});
});
Tip: res.sendFile is used to deliver files in Express applications.
Next, we will define a route to handle votes. When a request with an item_id is sent to this route, we want to increase the number of votes on that item, and broadcast the change to all our users.
app.get('/vote', (req, res) => {
  let item = req.query.item_id;
  pusher.trigger('counter', 'vote', {item: item});
  res.status(200).send();
});
In the code above, when a request is made to the /vote route, it gets the value of the item from the item_id key in the query string, then triggers a vote event on the counter channel, sending the item information as data to be broadcasted.
The trigger method has this syntax: pusher.trigger( channels, event, data, socketId, callback );. You can read more in it here.
We are broadcasting on a public channel as we want the data to be accessible to everyone. Pusher also allows broadcasting on private and presence channels, which provide functionalities that require authentication. Their channel names are prefixed by private- and presence- respectively, unlike public channels that require no prefix.
Typically, we should also save the new value of the number of votes to a database of some sort, so the data is persisted, but that is a bit out of the scope of this tutorial. You can implement this on your version!
Now we can start the server and listen on port 5000 for connections:
const port = 5000;
app.listen(port, () => { console.log(`App listening on port ${port}!`)});
The final server.js file will look like this:
/*
 * Initialise Express
 */
const express = require('express');
const path = require('path');
const Pusher = require('pusher');
const app = express();
app.use(express.static(path.join(__dirname)));

/*
 * Initialise Pusher
 */
const pusher = new Pusher({
  appId: 'YOUR_APP_ID',
  key: 'YOUR_APP_KEY',
  secret: 'YOUR_APP_SECRET',
  cluster: 'eu',
  encrypted: true
});

/*
 * Define app routes and reponses
 */
app.get('/', (req,res) => {  
  res.sendFile('index.html', {root: __dirname});
});

app.get('/vote', (req, res) => {
  let item = req.query.item_id;
  pusher.trigger('counter', 'vote', {item: item});
  res.status(200).send();
});

/*
 * Run app
 */
const port = 5000;
app.listen(port, () => { console.log(`App listening on port ${port}!`)});

Creating the App View

Now, we can fill index.html with some markup. I also included Foundation to take advantage of some preset styles:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.1/css/foundation.min.css">
  <title>JavaScript Decides</title>
</head>
<body>
  <div class="container text-center">
    <h3 class="title">
      Pusher Real-time Vote Counter.
      <h5 class="subheader">JavaScript Decides</h5>
    </h3>

    <div class="row">
      <div class="columns medium-6">
        <div class="stat" id="vote-1">0</div>
        <p class="subheader"><small>number of votes</small></p>
        <button class="button vote-button" data-vote="1">Vote for me</button>
      </div>
      <div class="columns medium-6">
        <div class="stat" id="vote-2">0</div>
        <p class="subheader"><small>number of votes</small></p>
        <button class="button vote-button" data-vote="2">Nah, Vote for me</button>
      </div>
    </div>
    <hr>
  </div>
</body>
</html>

Listening for Events from Pusher and Updating the Vote Count

To work with Pusher on the client side, we need to include its JavaScript library. We’ll do so at the bottom of index.html:
<script src="https://js.pusher.com/4.0/pusher.min.js"></script>
Then, initialising Pusher with our app credentials:
const pusher = new Pusher('YOUR_APP_KEY', {
  cluster: 'eu',
  encrypted: true
});
Note: Don’t forget to replace ‘YOUR_APP_KEY’ with its actual value
Next, we will subscribe to the counter public channel, which is the same channel we publish to on our server-side, and listen for vote events:
const channel = pusher.subscribe('counter');

channel.bind('vote', data => {
  let elem = document.querySelector(`#vote-${data.item}`),
      votes = parseInt(elem.innerText);
  elem.innerText = votes + 1;
});
Tip: You can also do Pusher.logToConsole = true; to debug locally
In the above code, we also defined a callback function, which accepts the data broadcast through Pusher as its parameter. We used this data to update the DOM with the new values of the vote counts.
Finally, we define an event listener for click events on our vote buttons. We also define a voteItem() function which will be fired whenever the buttons are clicked.
const voteButtons = document.getElementsByClassName("vote-button");

function voteItem() { 
  let vote_id = this.getAttribute("data-vote");

  // Make Ajax call with JavaScript Fetch API
  fetch(`/vote?item_id=${vote_id}`)
      .catch( e => { console.log(e); });
}

// IIFE - Executes on page load
(function() {
  for (var i = 0; i < voteButtons.length; i++) {
    voteButtons[i].addEventListener('click', voteItem);
  }
})();
Note: We make use of the JavaScript Fetch API for making an Ajax request. It is promise-based, and more powerful than the regular XMLHttpRequest, although a Polyfill might be needed for older browsers.
The final index.html file will look like this:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.1/css/foundation.min.css">
  <title>JavaScript Decides</title>
</head>
<body>
  <div class="container text-center">
    <h3 class="title">
      Pusher Real-time Vote Counter.
      <h5 class="subheader">JavaScript Decides</h5>
    </h3>

    <div class="row">
      <div class="columns medium-6">
        <div class="stat" id="vote-1">0</div>
        <p class="subheader"><small>number of votes</small></p>
        <button class="button vote-button" data-vote="1">Vote for me</button>
      </div>
      <div class="columns medium-6">
        <div class="stat" id="vote-2">0</div>
        <p class="subheader"><small>number of votes</small></p>
        <button class="button vote-button" data-vote="2">Nah, Vote for me</button>
      </div>
    </div>
    <hr>
  </div>

  <script src="https://js.pusher.com/4.0/pusher.min.js"></script>
  <script>
    const pusher = new Pusher('YOUR_APP_KEY', {
      cluster: 'eu',
      encrypted: true
    });

    const channel = pusher.subscribe('counter');

    channel.bind('vote', data => {
      let elem = document.querySelector(`#vote-${data.item}`),
          votes = parseInt(elem.innerText);
      elem.innerText = votes + 1;
    });

    const voteButtons = document.getElementsByClassName("vote-button");

    function voteItem() { 
      let vote_id = this.getAttribute("data-vote");

      // Make Ajax call with JavaScript Fetch API
      fetch(`/vote?item_id=${vote_id}`)
          .catch( e => { console.log(e); });
    }

    // IIFE - Executes on page load
    (function() {
      for (var i = 0; i < voteButtons.length; i++) {
        voteButtons[i].addEventListener('click', voteItem);
      }
    })();
  </script>
  </body>
</html>
And that’s it, we have a functional realtime vote counter!
To run the app:
node server.js
You can also get nodemon, so you can have automatic reloads on changes to your file. So instead, you could do: nodemon server.js.
Demo and Repo
Here is what the final app looks like:
Alternatively, you can view a live version here. You can open multiple browser windows to test the functionality.
The code for this tutorial is hosted on GitHub. You can always reference it if you need to. You can also clone it and make changes as you wish.
Conclusion
In this tutorial, we have learned how to start a basic JavaScript project, and give it realtime functionality using Pusher. We have also learned about Public channels, and how we can trigger events on these channels on the server-side, and listen for them on the client-side.
There are a lot of possibilities, with Pusher providing realtime functionality for our applications, especially in the creation of dashboard components. In the same way as a counter was created, we can also create tables, charts, and so on.
Pusher’s presence channels can also be used to implement a view counter, whenever a user visits your app.
Do you have any other cool use cases for Pusher, especially in a JavaScript application, let us know in the comments. Questions are also welcome!
The post How to build a realtime counter using JavaScript appeared first on Pusher Blog.