The JavaScript blog.


tutorials testing angularjs error-handling

AngularJS Form Errors, Angular Integration Tests

Posted on .

AngularJS: API Error Code Handling in Forms

When you're writing forms with Angular, it's not always clear how to handle errors in a reusable way. For example, what format should the server use to send back structured error message to the client? How do you use these responses to annotate fields with errors?

Szymon Kosno sent in AngularJS: API Error Code Handling in Forms, a tutorial that shows how to use error handling without explicit error handling in view controllers. It makes suggestions for how to structure detailed JSON error responses, and how to support different types of errors: for example, global errors and errors for specific form fields.

The form's markup uses an api-validate directive for input elements that should be validated by the server and will show error annotations. This allows the underlying error handling code to determine that the field is API error aware, so errors can be displayed or hidden as required.

With the right directives and services, Szymon is able to remove custom error handling code, which really cleans up the associated controllers. This article is useful if you've ever been confused about how to handle server-side errors, which you should always do for security and sanity.

Angular Integration Tests

Torgeir Helgevold sent in Angular integration tests, which gives some background to integration tests and includes a detailed example towards the end of the article.

In the following example I will demonstrate how to test a series of nested components with shared state. My sample code includes a parent directive where a user can add an inputed number to a list by clicking a button. Nested within there are two directives, one for calculating the sum of all items, and a second directive for building a comma separated string from the items in the list.

The example uses Angular's controllerAs syntax to simulate isolated scopes and pass changes. If you've ever used something like Selenium for integration tests, then you might want to compare Torgeir's approach if you're looking for something more lightweight and focused.


tutorials books

Holiday Reading for JavaScript Programmers

Posted on .

Hemingway and JavaScript

If you're lucky enough to be enjoying a festive holiday right now, then you're probably starting to get bored of Christmas movies and long dark teatimes of the soul. Rather than knuckling down with the family to watch Elf for the umpteenth time, why not load up your favourite reading device with some programming books and articles?

Angus Croll sent in a copy of his book If Hemingway Wrote JavaScript (No Starch Press, $15.95), which makes comparisons between literary figures and programming styles. This book started as a blog post about Hemingway, and there are amusing posts on his blog, like Animals writing JavaScript. I thought it would be hard to stretch the original idea out into an entire book, but Angus uses the concept to explore the broader question of how we write and think about JavaScript:

JavaScript has plenty in common with natural language. It is at its most expressive when combining simple idioms in original ways; its syntax, which is limited yet flexible, promotes innovation without compromising readability. And, like natural language, it's ready to write. Some of JavaScript's more baroque cousins must be edited with an IDE (integrated development environment—a sort of Rube Goldberg machine for coding). JavaScript needs nothing more than a text file and an open mind.

The question of style in programming is usually approached with defensive trepidation, but the literary conceit allows Angus to present different stylistic ideas without judging them. For example, Virginia Woolf's poetic stream of consciousness is recreated with a mix of long lines and flexible use of semicolons:

If the semicolon is the period of JavaScript, then the comma operator is its semicolon. Programmer Woolf loves the comma operator, and in her happy numbers solution, she uses it to excess. The result is a dreamy, melancholic form of JavaScript (is there any other?) made dreamier still by the heavy, almost dangerous level of n alliteration and some gorgeously expressive pairings. In To the Lighthouse, Woolf writes of night's shadows: "They lengthen; they darken"; in her happy numbers solution we get the wistfully poetic numerals.shift(), numerals.length.

I commute across London everyday and read to pass the time. Over the years I've moved from pulp sci-fi to 20th century modernists and the classics, so this book is ideal for me. I'm not sure how many literary programmers there are, however, so this is definitely a novelty that I will cherish.

Other readers have also recently sent in some interesting resources that you might like to read over the holiday. Thai Pangsakulyanont's JavaScript for Automation Cookbook contains examples for Apple's new scripting system that allows you to control Yosemite applications with JavaScript. It includes iTunes, Safari, system events, and how to use CommonJS modules with Browserify, so you can actually make maintainable automation scripts.

Eugene Abrosimov sent in a big list of Backbone.js tutorials, articles, videos, and examples. There should be a few things on there to load up Instapaper/Pocket if you use Backbone.

And, just over a week ago I received the first print of my book, Node.js in Practice (Manning, $39.99). I wrote it with Marc Harter, and we've designed the book for intermediate to advanced Node developers. Our publisher, Manning, also publishes Node.js in Action (Manning, $35.99) which is well suited to new Node programmers.


tutorials libraries games reactive data-binding

BindingJS, 2D Space Shooter Part 2

Posted on .


BindingJS (GitHub: rummelj / bindingjs, License: MPL) by Johannes Rummel is a data binding library that seeks to separate data binding declarations from HTML. It has a Less-inspired syntax for defining bindings, which you can put in a script element with the text/binding type.

JavaScript is used to set things up, and the API is fluent, so you can chain calls to configure things like the template fragment that a binding document applies to.

The binding syntax is similar to CSS, but because it's influenced by Less you'll find it easier to group properties with nesting.

Data is accessed through "adapters", so it's fairly easy to customise it to existing applications:

There are multiple view adapter such as value, text, attr or on that are already included in BindingJS. The qualifier of an adapter is a static instruction for the Adapter and is written directly behind the prefix, if that is only one character long. Otherwise it is separated by a colon from the prefix.

I like the idea of a CSS selector data binding language, but the expressions it uses are terse so it may take some effort to get the hang of BindingJS. Also, I think it would work well with custom elements, so it would be worth experimenting with that.

Part 2 of How to Make a 2D Space Shooter in Unity

Thomas Palef sent in part 2 of How to Make a 2D Space Shooter in Unity. This is the tutorial series that uses Unity's JavaScript API. In this part Thomas adds enemies and collision handling as well.


tutorials games node modules slideshows

Slideshow, Unity and JavaScript

Posted on .


What do you do when Apple and Microsoft do everything they can to pull us into their walled development environment gardens? One answer is to unify both environments using a sane Node API. Ralf S. Engelschall sent in Slideshow (GitHub: rse / slideshow, License: MPL, npm: slideshow), a module for remote controlling and monitoring presentation programs like PowerPoint and Keynote.

He also wrote slideshow-forecast, which is a cool CLI and GUI for monitoring slideshows:

The motivation for this is that for large presentations which have to be given in multiple variants for different timeslots it is very hard to determine the later presentation duration during preparation time. Instead of performing lots of different dry-runs after each preparation, this tool provides a duration prognosis already during preparation time.

The slideshow command-line program itself lets you drive an application with commands like boot, open file, and start. You can also goto a given slide and stop the presentation at the end.

Internally it uses Microsoft's cscript or Apple's osascript to communicate with the target application, so you don't have to worry about strange AppleScript or COM incantations.

How to Make a 2D Space Shooter in Unity


The Unity game engine is hugely popular with game developers. Many of the indie games that I've enjoyed have been made with it, and if I had the time I'd love to make something with it. I was aware Unity supports C#, but I didn't know it has a compiled JavaScript language as well.

Thomas Palef has written a new tutorial about using JavaScript with Unity called How to Make a 2D Space Shooter in Unity. It shows you how to get started making a game with Unity's UI, and includes some simple JavaScript for handling firing a bullet.

If you're interested in Unity but thought it was something that only desktop developers can get into then you might enjoy following this tutorial.


tutorials games phaser

Tutorial: Build a Game with Phaser

Posted on .

This is a guest post written by Thomas Palef, the author of Discover Phaser and the 12 Games in 12 Weeks challenge.


In this tutorial I will show you how to use Phaser to build a really simple retro breakout clone. Phaser is a simple yet powerful JavaScript framework for making HTML5 games.

Game screenshot

You can play the finished game we are going to make here.

Set Up

You should download this empty template that I made for this tutorial. In it you will find:

  • phaser.min.js, the Phaser framework v2.0.5
  • index.html, where the game will be displayed
  • main.js, a file where we will write all our code
  • assets/, a directory with 3 images (ball.png, paddle.png and brick.png)

You should also download the code editor Brackets, that will make it easier for starting a web server during development.

Empty Game

Let's start by creating an empty Phaser project. Add this code inside the main.js file:

// Define our main state
var main = {  
  preload: function() {
    // This function will be executed at the beginning     
        // That's where we load the game's assets  

  create: function() { 
    // This function is called after the preload function     
        // Here we set up the game, display sprites, etc. 

  update: function() {
    // This function is called 60 times per second    
        // It contains the game's logic     

// Initialize Phaser, and start our 'main' state 
var game = new Phaser.Game(400, 450, Phaser.AUTO, 'gameDiv');  
game.state.add('main', main);  

This will create a 400x300 black rectangle on the screen. All we have left to do is to fill the preload, create, and update functions to build our breakout clone.

Add the Paddle

Let's focus on creating the paddle first. We load it in the preload function, initialize it in the create function, and make it move in the update function:

preload: function() {  
  // Load the paddle image
  game.load.image('paddle', 'assets/paddle.png');

create: function() {  
  // Initialize the physics system of the game

  // Create a variable to handle the arrow keys
  this.cursor = game.input.keyboard.createCursorKeys();

  // Create the paddle at the bottom of the screen
  this.paddle = game.add.sprite(200, 400, 'paddle');

  // Enable the physics system for the paddle

  // Make sure the paddle won't move when hit by the ball
  this.paddle.body.immovable = true;

update: function() {  
  // If the right arrow is pressed, move the paddle to the right
  if (this.cursor.right.isDown) 
    this.paddle.body.velocity.x = 350;

  // If the left arrow if pressed, move left
  else if (this.cursor.left.isDown) 
    this.paddle.body.velocity.x = -350;

  // If no arrow is pressed, stop moving
    this.paddle.body.velocity.x = 0;  

Test the Game

Now it's time to test our game. Open the whole directory in the Brackets editor, select the index.html file, and click on the small bolt icon in the top right corner. It will launch a live preview of the game, where you should have a paddle that you can move with the arrow keys.

If you don't want to use Brackets, then you'll have to use a local web server to test the game.

Add the Bricks

Now let's add a dozen bricks to the game.

Start by adding this to the preload function:

// Load the brick sprite
game.load.image('brick', 'assets/brick.png');  

Then add this to the create function:

// Create a group that will contain all the bricks
this.bricks = game.add.group();  
this.bricks.enableBody = true;

// Create the 16 bricks
for (var i = 0; i < 5; i++)  
  for (var j = 0; j < 5; j++)
    game.add.sprite(55+i*60, 55+j*35, 'brick', 0, this.bricks);

// Make sure that the bricks won't move
this.bricks.setAll('body.immovable', true);  

Add the Ball

Now that we have a paddle and some bricks, it's time to add the ball.

Add this in the preload function:

// Load the ball sprite
game.load.image('ball', 'assets/ball.png');  

And add this in the create function to initialize the ball:

// Create the ball with physics
this.ball = game.add.sprite(200, 300, 'ball');  

// Add velocity to the ball
this.ball.body.velocity.x = 200;  
this.ball.body.velocity.y = 200;

// Make the ball bouncy 
this.ball.body.collideWorldBounds = true;  
this.ball.body.bounce.x = 1;  
this.ball.body.bounce.y = 1;  

Handle Collisions

The only thing left to do is handle collisions. And it turns out this is super simple with Phaser -- just add these 2 lines of code to the update function:

// Make the paddle and the ball collide
game.physics.arcade.collide(this.paddle, this.ball);

// Call the 'hit' function when the ball hit a brick
game.physics.arcade.collide(this.ball, this.bricks, this.hit, null, this);  

Next, create the new hit function, just below the update function:

hit: function(ball, brick) {  
  // When the ball hits a brick, kill the brick

And we are done! you can now play a really simple breakout clone made in less than 50 lines of JavaScript.


The game is working, but it's a little bit boring. With Phaser it's really simple to add sounds effects, animations, transitions, and so on to make a game better.

If you want to learn more about Phaser, I can recommend you to check out the first and only Phaser ebook currently available: Discover Phaser.

Phaser cover