Using ECMAScript6 today

1. Introduction

Although ECMAScript6 has not been officially released yet, we can play around with new language features today. There are tools such as Traceur or Babel which are able to convert ECMAScript6 into ECMASciprt5, thus we are able to run the code in every browser. So let’s try to run the snippet below, which leverages destructuring assignmentusing those tools

2. Using Traceur

I’ll start from Traceur first. First of all we have to install it, so run in console (I am using gulp as my build system)

Then we have to write simple gulp task which:

  • grabs all of our js files
  • runs the code analysis using JsHint
  • transpiles source files into valid ECMAScript5
  • concatenates the result into single file
  • generates source maps (for debugging proposes)

Having our result file ready, now we can add a script tag in html pointing to app.all.js. However at this point in the runtime we will get an error.

ECMAScript6 today
Quick look at the generated app.all.js file reveals the problem

Transpiled code has references to $traceurRuntime objects, so in order to make our code work, we have to add additional script tag pointing to traceur-runtime.js. You can easily get the sources with bower, just run in console

Now everything should work and in console we’ll get expected result
ECMAScript6 today
As you could see in example above Traceur generates overcomplicated code which makes debugging of the original sources (using source maps) a painful process. Just take a look at the following screenshot
ECMAScript6 today
fortunately Babel doesn’t seem to have these drawbacks.

3. Using Babel

Let’s modify our gulp build script to use Babel instead of Traceur

And basically that all, we are ready to go. Babel doesn’t require any runtime dependencies, generated code is simple

and even source maps seem to work correctly.
ECMAScript6 today
So when it comes to me I choose Babel. Source code for this post can be found here

Using ECMAScript6 today

AngularJS – extending existing services using decorator

One of the features I miss the most in AngularJS is ability to easy unsubscribe event handlers. There is no convenience function opposed to $on, so in order to unsubscribe event, we have to call method returned by $on function

However in my opinion this approach fails in real life scenarios, because usually we are subscribed to more than one event – thus we have to have multiple local variables for detaching listeners. Fortunately AngularJS provides an easy way to extend existing services with some new functionalities – we can achieve that by using $provide service. This service exposes decorator method, which is able to intercept creation of any service, so we are able to augment it with some new functions. The best moment to call $provide.decorator method is during module configuration, thanks to this approach we are sure that our custom logic is invoked before module is started.

In my case I wanted to extend $rootScope with new method $un for unsubscribing events, so I called method decorator with parameter ‘$rootScope’ (note single quotation marks) – this tells Angular that I will be modifying $rootScope service

Because I passed ‘$rootScope’ as a first argument of $provide.decorator method, the $delegate parameter in extendRootScope function is actually a $rootScope service. Now having access to the service I can augment it with my custom logic for detaching event handlers.

Entire code listing looks then as follows

From now on, you can unsubscribe events handlers simply by calling $un method

and our listener will react only once

Source code for this post can be found here

AngularJS – extending existing services using decorator

WinJS – AuthenticateAndContinue and “remote procedure call failed” exception

A while ago I started playing around a bit with JavaScript on Windows Phone. I wanted to create very simple app using AngularJS but of course I also had to use some WinJS features (for integration with device ). One of the things I needed to implement was authentication/authorization using OAuth. According to WinJS documentation it should be pretty straightforward – just use Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAndContinue method with appropriate URLs. Of course I wanted authentication/authorization to be called before navigating to any screen, so I slightly modified default WinJS template and my code looked like that

Unfortunately all I got was this strange exception
remote procedure call failed

The exception itself originated somewhere from WinJS framework so I wasn’t able to debug it at all. It took me a while to figure this out but after all it turned out, that all you have to do, to make it work is to “schedule” call of AuthenticateAndContinue method using WinJS.Utilities.Scheduler

After this change entire code listing looks like that

After this procedure we should be successfully redirected to the requestUrl, in my case to Facebook login page

WinJS – AuthenticateAndContinue and “remote procedure call failed” exception

AngularJS – dependency injection

There are couple of ways of injecting dependencies into AngularJS components. The most common one is just to specify the dependency name in the function’s argument list

However this technique fails in real life scenarios, because for production we usually (or rather always) minify and uglify javascript files. Uglify proces renames our variables and due to the fact that dependencies are resolved by name, AngularJS is not able to find appropriate services, directives etc. To overcome this limitation, we can enclose our function definition into an array, and specify dependencies as a string literals. Our original code becomes then

Although this works fine even after minifying and uglifiyng js files, for me this code is hard to read. That is why I like to use yet another technique. This technique leverages variable hoisting and $inject property

As You can see I extracted controller function into separate variable “shellController” and listed all necessary dependencies in $inject array

It is even possible to enhance a bit this example and make it a little less error prone. With the current implementation we have to make sure that order of properties in $inject array is the same as in function declaration. It is easy to keep track of that if we have just a couple of dependencies, but it might be a bit of a pain if we start to add, remove or edit them. Fortunately we can automate this task and basically autogenerate $inject array. In order to do that I like to use Gulp (although it is also possible to use Grunt). First of all we have to install Gulp. There is great tutorial how to do that in here Having Gulp on board we have to install additional packages: gulp-rename and gulp-ng-annotate. In order to do that type into command line

Now we can create gulp.js file which should look more or less like that

We can run this task typing into command line

gulp dependency injection
And as a result our original code (notice lack of dependeny annotations – no $inject arrray)

Will be transformed into

AngularJS – dependency injection

Fixing missing semicolon issue using WebStorm

Recently in the company I work for, we’ve been trying to improve Javascript code quality. After hooking up JSlint into our build script, it turned out that the most common issue with our code is missing semicolon at the end of statements. Fixing all warnings manually would be very boring task, that is why I started searching for alternative solution. Fortunatelly once again, WebStorm came for the rescue. As you probably know WebStorm has it’s own code inspection tool which indicates problems with code. However except that, this tool can also fix these problems automatically. Here is a little demonstration. Let us start with simple code.

In the listing above, there are two lines with missing semicolon (in function getView). Let fix them using Webstorm code inspection tool.
First of all, we have to make sure that appropriate inspection options are selected. In order to do that, let’s choose “Settings” from menu “File”. In the opened window, go to “Settings” and select options presented in the picture below.
In the next step, from menu “Code” choose “Inspect code”
In the opened window, we can change inspection profile or inspection scope, but usually we can go with default settings
After inspection is done, at the bottom of the screen you will see results
Now, we can quickly fix them by using context menu and clicking “Terminate statement”
Here is the result of fixing operation
missing semicolon

Fixing missing semicolon issue using WebStorm