Build a voting system with Ember.js
You will need Node and npm installed on your machine.
Introduction
In this tutorial, we are going to build a basic voting app with Ember.js that displays the live results of votes on a doughnut chart as they come in. Pusher will be used here to respond to votes and dynamically update the chart in all browsers in realtime. The results will be instant as depicted in the image below:
A simple realtime voting application like this can improve the conventional way of casting and collecting votes, and also facilitate the live update of results for everyone involved to see. This improves transparency and makes the experience more interactive.
In this realtime demo, users will be able to vote for the fans that they consider the best by clicking on the image. This will immediately increase the points of such country as it will be displayed on the chart.
Prerequisites
It is important that you have Node.js and npm installed on your machine, learn how to install Node.js and npm here. A quick run-down of the core technologies we will be using include:
- Ember.js: a productive frontend framework built for ambitious web developers.
- Pusher: a Node.js client to interact with the Pusher REST API
- Express: Node utility for handling HTTP requests via routes
- Axios: a promise-based HTTP client that works both in the browser and in a Node.js environment.
- Body Parser: attaches the request payload on Express’s
req
, hencereq.body
stores this payload for each request. - CanvasJS: a responsive HTML5 Charting library for data visualization.
Getting started
The most convenient and recommended way of getting an Ember app up and running with a single command is by using the Ember CLI tool. You can install it with npm, open your terminal and type this command:
npm install -g ember-cli
The Ember CLI will give us access to the ember
command that will be used to set up our project easily.
Creating the voting application
We can now proceed to create our application by using the ember new
command. Open up the terminal on your machine and run a command that will create an application named realtime-voting-ember
in your project directory:
ember new realtime-voting-ember
Next, change directory into the newly created project and start the development server:
// change directory
cd realtime-voting-ember
// start the development server
ember serve
This will start the development server on http://localhost:4200. Open your favorite browser and navigate to that URL, you should see a default welcome page by Ember.js as shown below:
Installing server dependencies
Run the following command to install the dependencies required for this project using:
npm install --save axios pusher pusher-js
npm install --save body-parser cors dotenv express
npm install --save canvasjs babelify babel-preset-es2015 babel-preset-stage-1
ember install ember-browserify
Pusher account setup
Head over to Pusher and sign up for a free account.
Create a new app by selecting Channels apps on the sidebar and clicking Create Channels app button on the bottom of the sidebar:
Configure an app by providing basic information requested in the form presented. You can also choose the environment you intend to integrate Pusher with to be provided with some boilerplate code:
You can retrieve your keys from the App Keys tab:
Setting the environment variables
Create a .env
file in the root directory of your application and add your application credentials as obtained from your Pusher dashboard as follows:
PUSHER_APP_ID=YOUR_APP_ID
PUSHER_APP_KEY=YOUR_APP_KEY
PUSHER_APP_SECRET=YOUR_APP_SECRET_KEY
PUSHER_APP_CLUSTER=CLUSTER
We will make use of the variables specified in the above snippet later in our project. And do ensure that you replace YOUR_APP_ID
, YOUR_APP_KEY
, YOUR_APP_SECRET_KEY
and CLUSTER
placeholders with the appropriate credentials.
Setting up the server
As stated earlier, a user will only be able to vote by clicking on an image of the chosen option from the list of fans displayed.
This click event will result in a process that needs to be managed by a server. So we’ll use Express and Node to set up a simple server that will receive the id
of the country selected and publish it to a designated channel alongside the points required to update the chart.
Since the Ember application that we configured earlier is running on a different domain, we’ll enable CORS in order to ensure communication between the Express server and Ember.
Create an app.js
file in the root directory of your application and add the following code snippet to it to set up the server:
// app.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const Pusher = require('pusher');
require('dotenv').config();
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
const pusher = new Pusher({
appId: process.env.PUSHER_APP_ID,
key: process.env.PUSHER_APP_KEY,
secret: process.env.PUSHER_APP_SECRET,
cluster: process.env.PUSHER_APP_CLUSTER,
encrypted: true
});
app.set('port', process.env.PORT || 3000);
app.post('/vote', (req, res) => {
const payload = {
fans: req.body.id,
points: 10
}
pusher.trigger('poll', 'vote', payload);
res.send(payload)
})
app.listen(app.get('port'), () => {
console.log("Listening on port " + app.get('port'));
})
Here we loaded all the necessary middlewares for the Express server and then configured Pusher using the credentials we added to our environment variables earlier.
Furthermore, we also created the /vote
endpoint that will receive and process the selected id
sent in from our Ember app. Finally, we triggered an event named vote
to Pusher Channels on a channel called poll
. The poll
channel holds a payload that contains the id
of the country selected by the user and the points to update the chart.
Open another terminal and run the command below to start the server on http://localhost:3000
node app.js
This will log a message to the console as shown by the image below:
Defining your routes
Routes in Ember.js plays a significant role in mapping an endpoint to a particular template file. To create a route for our application, we’ll make use of Ember generators to automate the process. Run the command below in the terminal from the root directory of your project:
ember generate route realtime
This will create a route file ./app/routes/realtime.js
and a template file for the route at ./app/templates/realtime.hbs
. The route file is the route handler and defines the data that should be loaded and what should happen when the template file is rendered.
In our case, we need to pass a dataset that will contain the imgSrc
, fans
and the id
of each country to the template file. Now, open the ./app/routes/realtime.js
and update it with the following content:
// ./app/routes/realtime.js
import Route from '@ember/routing/route';
const dataset = [
{
"imgSrc":"http://res.cloudinary.com/yemiwebby-com-ng/image/upload/v1529405850/nigerians_jojjpz.jpg",
"id":"Nigeria",
"fans":"Nigerian fans"
},
{
"imgSrc":"http://res.cloudinary.com/yemiwebby-com-ng/image/upload/v1529405850/mexican-fans_wzfkd9.jpg",
"id":"Mexico",
"fans":"Mexican fans"
},
{
"imgSrc":"http://res.cloudinary.com/yemiwebby-com-ng/image/upload/v1529405850/brazil_ik4yu5.jpg",
"id":"Brazil",
"fans":"Brazilian fans"
},
{
"imgSrc":"http://res.cloudinary.com/yemiwebby-com-ng/image/upload/v1529405850/argentina_n5e2ye.jpg",
"id":"Argetina",
"fans":"Argentina fans"
}
]
export default Route.extend({
model() {
return dataset;
}
});
Here, we declared a dataset
that will be rendered on the /realtime
endpoint. Next, we’ll update the template file. Locate ./app/templates/realtime.hbs
and paste the code below in it:
{{!-- ./app/templates/realtime.hbs --}}
<div class="main">
<div class="container">
<h1><b>Vote :</b> Which 2018 world cup team has the best fans</h1>
{{#voting-app poll=model}}{{/voting-app}}
</div>
</div>
We passed the model to a component named voting-app
. This will allow us to easily loop over the dataset
and attach a click event to the images. We’ll create this component in the next section.
Creating the UI components
Ember supports the usage and sharing of UI elements on multiple pages. We will leverage this and generate the voting-app
component for our application.
The Ember component generally consists of two parts: a JavaScript component file that defines behavior and a Handlebars template that defines the markup for the component’s UI.
Voting app component
Run the command below to generate the voting-app
component:
ember generate component voting-app
Voting app component file
Add the following content to ./app/components/voting-app.js
:
// ./app/components/voting-app.js
import Component from '@ember/component';
import CanvasJS from 'npm:canvasjs';
import axios from 'npm:axios';
import Pusher from 'npm:pusher-js';
let dataPoints = [
{label: 'Nigeria', y:1},
{label: 'Mexico', y:1},
{label: 'Brazil', y:1},
{label: 'Argetina', y:1}
]
export default Component.extend({
init() {
this._super(...arguments);
const chart = new CanvasJS.Chart('vote-chart-container', {
animationEnabled: true,
theme: 'theme1',
title: {
text: 'The best fans'
},
data: [
{
type: 'doughnut',
dataPoints: dataPoints
}
]
});
chart.render();
// Initialize Pusher
var pusher = new Pusher('YOUR_APP_KEY', { // update your APP_KEY
cluster: 'CLUSTER',
encrypted: true
});
var channel = pusher.subscribe('poll');
channel.bind('vote', (data) => {
dataPoints = dataPoints.map(x => {
if (x.label == data.fans) {
x.y += data.points;
return x;
} else {
return x;
}
});
chart.render()
});
},
actions: {
getElement(e) {
var id = e.target.id;
axios.post('http://localhost:3000/vote', {id});
}
}
});
First, we imported the required modules for this component and we added a dataPoints
array that will serve as the initial data source for the chart. The objects in the array have a uniform structure of label
, which stores the name of the country and y
which stores the points.
In addition, we used the Chart
constructor function to create a chart by passing the basic configuration for the chart which includes the dataPoints
. The chart is rendered by calling render()
on the constructor function instance.
Next, we initialize Pusher with the APP_KEY
and CLUSTER
as obtained from our Pusher account dashboard and then proceeded to use the subscribe()
method from Pusher to subscribe to the created poll
channel, update the dataPoints
variable and re-render the chart with render()
.
Finally, the getElement()
action was used to get the id
of the item clicked and POST
it to the server. This action will be triggered once a user clicks on an image in the template file for this component.
Don’t forget to replace the YOUR_APP_KEY
and CLUSTER
placeholder with the appropriate details from your Pusher account dashboard.
Voting app component template
Earlier, we passed the dataset
from the template file for the realtime
route to this component
in ./app/templates/realtime.hbs
. So here, we’ll loop over each item in the dataset
. Open ./app/templates/components/voting-app.hbs
and edit as shown below:
{{!-- ./app/templates/components/voting-app.hbs --}}
<div class="col-md-12">
<div class="row">
{{#each poll as |data|}}
<div class="col-md-3">
<div class="poll-device">
<img onclick={{action 'getElement'}} src="{{data.imgSrc}}" alt="" id="{{data.id}}">
<p class="text-center caption">{{data.fans}}</p>
</div>
</div>
{{/each}}
</div>
</div>
Update the app template
Update the application template file by adding the container where the chart will be rendered:
{{!-- ./app/templates/application.hbs --}}
<div id="vote-chart-container"></div>
{{outlet}}
Stylesheet
To add some minimal styling to the page, open ./app/styles/app.css
and paste this code in it:
// ./app/styles/app.css
@import url('https://fonts.googleapis.com/css?family=Spectral');
*, *:before, *:after {
box-sizing: border-box;
}
html, body {
font-family: 'Spectral', serif;
height: 100%;
}
.main {
height: 100%;
background-color: #FAFAFA;
}
.container {
padding-top: 20px;
padding-bottom: 20px;
}
h1 {
text-align: center;
}
.caption {
font-weight: bold;
}
.poll-device {
border: 1px solid #EDEDED;
}
.poll-device p {
padding: 10px;
}
.poll-device.selected {
background: #EDEDED;
}
.poll-device:hover {
background: #EDEDED;
cursor: pointer;
}
.poll-device img {
width: 100%;
height: auto;
display: block;
margin: 0 auto;
}
#vote-chart-container {
height: 300px;
width: 100%;
background: #f5f5f5;
}
Updating the index page
Open the ./app/index.html
file and include the CDN file for Bootstrap to enhance the styling and layout of our application. Open up the file and add update as shown below:
<!-- ./app/index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>RealtimeVotingEmber</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
{{content-for "head"}}
<link integrity="" rel="stylesheet" href="{{rootURL}}assets/vendor.css">
<link integrity="" rel="stylesheet" href="{{rootURL}}assets/realtime-voting-ember.css">
<!-- add the CDN file -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
{{content-for "head-footer"}}
</head>
<body>
{{content-for "body"}}
<script src="{{rootURL}}assets/vendor.js"></script>
<script src="{{rootURL}}assets/realtime-voting-ember.js"></script>
{{content-for "body-footer"}}
</body>
</html>
Testing the application
Stop the Ember development server if it is currently running by typing Ctrl + C
in the terminal and restart it with ember serve
. In addition, don’t forget to also run node app.js
from another terminal to start the Express server in case you haven’t done that. Next, open http://localhost:4200/realtime to test the application.
If you wish to access the application without adding the /realtime
path, you can edit the application’s router file ./app/router.js
by updating the path as shown below:
// ./app/router.js
import EmberRouter from '@ember/routing/router';
import config from './config/environment';
const Router = EmberRouter.extend({
location: config.locationType,
rootURL: config.rootURL
});
Router.map(function() {
// edit the path
this.route('realtime', { path: '/'});
});
export default Router;
Now if you visit http://localhost:4200, you should still see the application fully functioning.
Conclusion
Although a voting system definitely has more features than what we have implemented here, I anticipate that with the basic knowledge gained from this tutorial you can easily get more creative and improve your existing project or new ones.
I hope you found this tutorial useful. The complete source code can be found here on GitHub.
20 June 2018
by Christian Nwamba