Automated testing with Grunt and Jasmine

On my last post Conway’s Game of Life I’ve used jasmine for testing my code.

Now, I would like to show how to automate the process of running all the tests.  and for this I will be using Grunt (v0.4.5).

This will be more like a recipe because there are already several good tutorials about grunt and jasmine, so if you’re new to Grunt or Jasmine, I advise you to get some basic reading first.

So let’s do this!

1. Because Grunt is built on Node, we have to install node and npm.

2. Open the command line.

3. install Grunt command line by running the following command:

npm install grunt-cli -g

-g will make it global

Note: on version 0.4 grunt was separated in grunt command line and grunt engine. Grunt command line typically is installed globally and Grunt engine locally.

4. Go to the project directory.

5. Install Grunt engine:

npm install grunt

6. Create a package.json. This can be done by hand or automatically using the command:

npm init

This will ask you a few questions and by the end it will create the file.

7. Install jasmine plugin for grunt:

npm install grunt-contrib-jasmine --save-dev

The optional flag –save-dev will save our dependencies on our file package.json

Note: This command will also install phantom.js which is how it runs the tests

8. Create a gruntfile.js with the configuration needed

 module.exports = function(grunt) {
     // jasmine configuration - indicates the source files, the specs files and vendor files
     jasmine: {
       pivotal: {
         src : 'lib/js/*.js',
         options: {
           specs : 'spec/GameSpec.js',
           vendor: [

 // load plugins

 // Test task
 grunt.registerTask('test', ["jasmine"]);


9. Run the tests:

grunt test

And you can check that all tests are passing:

Webucator, a provider of JavaScript training, produced a nice little video inspired on this post. You can watch, step by step, how easy is to test javascript with Grunt and Jasmine.

HTML5 Conway’s Game of Life

I have created a HTML5 version of the Conway’s Game of Life.

The “game” is a zero-player game, meaning that its evolution is determined by its initial configuration and does not require any other input. The “game” is based in a grid with cells. Each cell has only 2 states: alive and dead. There are only 4 rules that determines how the game evolves:

  1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
  2. Any live cell with two or three live neighbours lives on to the next generation.
  3. Any live cell with more than three live neighbours dies, as if by overcrowding.
  4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

You can try it here.

I used javascript, knockout and Jasmine and the source code is available on my Github.


Understanding Javascript Publish/Subscription

One of the most interesting design patterns used on web development is the Publish/Subscribe. This pattern, also known as Pub/Sub, fits like a glove on the browser, mainly because the DOM is event driven, it uses events as its main interaction with API scripts. However, events aren not restricted to the DOM and you can have your own events on your API.

Pub/Sub offers a way to handle communication between various parts of a whole system. In short, subscribers want to be notified when something interesting happens and publishers want to notify, to those interested, that something has happened.

Pub/Sub diagram

Pub/Sub diagram

So this is the idea, a client 1 say for instance “I want to be notified when the data changes” and client 2 says “The data has changed!”.
Now that client 1 has been notified, he can update the data on the page for instance.

Without Pub/Sub, this works as well, the main difference is that the publisher needs to know about the other clients. In this case, after data changes, client 2 needs to call directly client 1, which would sound like “Hi client 1, data has changed!”.
This means client 1 and client 2 are tightly connected. This scenario starts to be complex with the number of clients growing, making the maintenance of your code too dificult. And what if one client is not there or is not right implemented? Will the other clients be afected?

What Pub/Sub introduces is loose coupling, the publisher doesn’t need to know who are the clients or how many are they. Neither the subscribers need to know about publishers or other subscribers. If one fails the other ones will keep working normaly.

On the other hand this decoupling also presents as its disadvantage, mainly because the publisher and subscribers don’t have any guarantee that everything is working, there is no guarantee that subscribers will be notified neither publishers have the guarantee that anyone is listening.

Event though I think the advantages are much more valuable than the disadvantage, however, the Pub/Sub pattern doesn’t apply to every application, and there are situations more suitable than others.

For instance, this pattern is commonly used on MVC applications (or some variation), where the View subscribes to changes on the models, and react properly when the Model notifies about its changes.

Normaly Javascript frameworks and libraries, and not necessarly MVC frameworks, implement this pattern and lets you use it out of the box, for instance, if you are using jQuery you can use Custom Events.

However, I want to show how easy is to implement your own version of Pub/Sub so that you understand even better what happens.

Below you can see my tiny implementation and I hope the code and comments will be self explanatory.

* Pub/Sub implementation

var pubsub = (function () {

 // store events subscribed
 // events = { eventName : [callback1, callback2, ...] }
 var events = {};

 // publish the event with the specified data
 function publish(eventID, data) {

   if (!events[eventID]) {

   var len = events[eventID].length;

   while (len--) {


 // subscribe to an event
 // passing the event name and the callback function
 function subscribe(eventID, callback) {

   if (!events[eventID]) {
     events[eventID] = [callback];
   } else {

   // returns eventID and the position index on the array
   // so that can be unsubscribed if needed
   return {
     eventID : eventID,
     index : events[eventID].length - 1

 // unsubscribe from an event passing the returned data got upon subscription
 function unsubscribe(subscription) {

   if (!events[subscription.eventID]) {

   events[subscription.eventID].splice(subscription.index, 1);

 return {
   publish : publish,
   subscribe : subscribe,
   unsubscribe : unsubscribe


And now, a short example of how this can be used. We have a list of items that we can add to the basket and we have two different vies of the basket, a simple one that shows only the total items and a detailed one where shows the items and quantities. When an item is added to the basket, the views will be notified and will refresh the data.

* on DOM ready handle adding to cart action
* demo.js

$(function () {

  // Add an item to the cart
  $('.add-to-cart').on('click', function() {

    //get product
    var product = $(this).prev('div').text();

    // publish event
    pubsub.publish('addToCart', product)

* The view that shows the total items on cart
* simpletrolley.js

var simpleTrolley = (function($){

var total = 0,
$display = $('#total-items');

// notification when an item is added to the cart
pubsub.subscribe('addToCart', function() {

  total ++;

  // update total

// update total items on the view
function updateTotal() {


* The view that shows the items detail and quantities on cart
* completetrolley.js

var completeTrolley = (function(){

  var items = {},
  $trolley = $('#trolley');

  // notification when an item is added to the cart
  pubsub.subscribe('addToCart', function (product) {

    // save info

    if (!items[product]) {
      items[product] = 1;
    } else {
      items[product] ++;

    // update view

  // update items on the view
  function updateItems(product) {

    // append to the view if item is not in the list
    // otherwise only update quantity

    var li = $trolley.find('li[data-product="' + product + '"]');

    if (li.length === 0) {
      $trolley.append('<li data-product="' + product + '">' + product + ': <span class="quantity">1</span></li>');
    } else {


You can run the Live Demo and also get the source code from GitHub.

I hope that it became clear the advantages of using Pub/Sub and that you now have a better understanding of it, either if you use an already implement version or you want to implement it yourself.

Scrolling background on Canvas

In this post I will show how to implement a scrolling background on the canvas.

Actually this is something very easy to achieve. The trick is that we have to draw the image twice, one for the top of the image and the second for the remaining part.

If you want, you can see the final result here and the source code on my Github page.

We start with the window onload event. We check if canvas is supported, if not we send an alert.

window.onload = function () {
 // get canvas
 var canvas = document.getElementById('canvas');
 // get context
 var ctx = canvas.getContext && canvas.getContext('2d');
 if(!ctx) {
 alert("Your browser is not supported!");
 } else {
 // start
 start(canvas, ctx);

After checking that the canvas is supported we start by loading the image.

var start = function (canvas, ctx) {
 // load image
 var img = new Image();
 img.onload = function () {
 // start animation
 animateBg(canvas,ctx, img);
 img.src = 'lib/img/starBackground.png';

As you can see, we set a callback to run on the image onload event.

On this event we call our function that is responsible for the animation.

var animateBg = function (canvas, ctx, img) {
 // properties
 var y = 0;
 var speed = 2;
 var ch = canvas.height;
 var cw = canvas.width;

// our loop
 setInterval(function () {
 // draw botom part
 ctx.drawImage(img, 0, 0, cw, ch, 0, y, cw, ch);

// draw remaining part
 ctx.drawImage(img, 0, ch-y, cw, ch, 0, 0, cw, ch);

// increment y or reset y if reached the bottom
 y = y < ch ? y + speed : 0;
 }, 1000/30);

In this function, first we get some properties, the Y position of the image (set to 0 initially), the speed of the animation and the canvas size. Next I use the setInterval function to create the animation loop (which is not the best way, but for our demo it works just fine). In the loop, first we draw the bottom and then the remaining part. Finally we reset the Y if we reached the bottom of the canvas.

Oops, too fast? Ok, let just take a look at the drawImage. We are using all the parameters that the function provide to us.

void drawImage(
 in nsIDOMElement image, // the image
 in float sx, // source coordinate X
 in float sy, // source coordinate Y
 in float sw, // source width
 in float sh, // source height
 in float dx, // destination coordinate X
 in float dy, // destination coordinate Y
 in float dw, // destination width
 in float dh // destination height

So, for the top, the only thing that changes with time is the destination Y coordinate.

For the remaining part the only thing that changes with time is source coordinate Y, which will be the canvas height – Y coordinate.

And that is all we need to set up a scrolling background!

Tip of the week – run html pages from Github

Did you know you could easily run an HTML page from Github?

The solution is rawgithub !

Just go to the file you would like to run and click on raw button. This will show the page but served as text/plain and not text/html.

So that you run the file as text/html on the url just delete the dot from rawgithub.



Very nice to share code or show some demos, but, beware, this is not for production! This is not an alternative to hosting services!

Check Can I use on a production website?

Get into RequireJS


Hi all, welcome to Get Into RequireJS! If you have good skills on javascript and already knows about the Revealing Module Pattern, get ready because, I will go cut to the chase!

What is RequireJS?

RequireJS is a module loader. Its functionality is to load modules and take care of dependencies for you. When you define a module, you will identify its dependencies and RequireJS will load those dependencies in runtime and just when they are needed!

How to add RequireJS to the project?

RequireJs assumes that you have a specifc directory structure in your project. Of course you can override this settings, but for the demonstration I will follow the default structure, which is the following:


  • project.html
  • scripts/

Under the scripts folder, you will have all the javascript for your project. I always suggest to have the third party libraries separated from your files, so, in my demo I have the following structure:


  • blog.html
  • scripts/
    • app/
    • lib/
    • main.js

Where my code goes to app folder and third party goes to the lib folder.

In the html page you will just include the RequireJS:

<script data-main="scripts/main" src="scripts/lib/require.js"></script>

The data-main attribute, indicates to RequireJS, that once it is loaded, it will have to load the scripts/main.js file. There are other ways to do this, but this one, without any configuration, is definitely the simplest one. Note that I did not refer main.js but only main, this is because RequireJS expects to load only javascript files, so you can omit the extension when you refer your modules.

On the main.js, normally I have some RequireJS configuration and the first call to my application API:

// requirejs configuration

// Define baseUrl (the base folder for the js files)

// Define path to jQuery


  baseUrl: 'scripts',

  paths: {

    jquery: 'lib/jquery'



// Start the main app logic.


  function (blog) {



In the code to start the application, I am saying to RequireJS that I need the module blog and then I can call my function that starts the application. We will just see how that works.

How to define a module?

The structure of a RequireJs module, follows the Module Pattern

In my demo I have the following module (file app/blog.js):

define(['app/dataservice', 'app/presenter'], function(dataservice, presenter){

  var start = function(){



  return {

    start: start



The code indicates that the module blog, depends on dataservice and presenter modules. On the start function, I am calling getPosts on dataservice module and I am passing the renderPosts on the presenter module as callback (not the best way, but for demo purpose is fine).

Picking one of the dependencies modules, for instance the dataservice, it is very similar as it also follows the same structure:


  var getPosts = function(callback){



  return {

    getPosts: getPosts



Final notes

There are a lot of configuration that you can do, different ways to load modules but, this was a cut to the chase, just to show how easy is to use RequireJS. If you thought it was interesting and want to start using it, I suggest to take a look at the documentation first.

You can download my complete demo in Github.


Ajax requests on jsFiddle

Did you know that you could create XHR requests on jsFiddle? If you didn’t know,  just keep reading..

To improve user experience jsFiddle has created the echo features. One of its features is to provide to developers the possibility to create XHR requests. It is very simple to use:

  &amp;lt;div class='wrapper'&amp;gt;
  &amp;lt;p&amp;gt;JSON will be received in 3 seconds&amp;lt;/p&amp;gt;
  &amp;lt;div id='post'&amp;gt;&amp;lt;/div&amp;gt;

This is my HTML, a simple div with id=post will be appended with the response from the request.

To make a request, I have used jQuery and it looks like this:

// My request

  type: &amp;quot;POST&amp;quot;,
  url: '/echo/json/',
  dataType: &amp;quot;json&amp;quot;,
    json: JSON.stringify({
      text: 'Response from server',
    delay: 3
  }).done(function(response) {

// append data from response to my div
show_response = function(obj, result) {

My request is just a simple jQuery ajax() call. There are some things that we have to provide.

The data has to be a POST call.  The url points to   ‘/echo/json/’ because I’ve chosen json to represent my data, but there is other types available (including XML).  The ‘json’ object that you define on the request, will be the object that you’ll get on the response. The optional ‘delay’ parameter, it’s a time in seconds after which data should be returned.

And this is pretty much it! Simple and very useful if you, like me, use jsFiddle to share code samples, help anyone or just quick testings!

You can see the live example here.