I will speak at JavaZone 2015

I’m excited to announce that I will be speaking at JavaZone 2015! If you did not know already, JavaZone is the largest IT conference in Norway. Up to 2500 software engineers gather each year in Oslo to attend 2 days packed with presentations, lightning talks and workshops!

I will be doing an hour presentation on the upcoming Angular 2.0; “Angular 2 + TypeScript = true. Let’s Play!”. Make sure to book your ticket today and I will see you in September! 🙂

Advertisements

Proper Dependency Injection in Your AngularJS TypeScript Apps

I’ve witnessed quite a lot of legacy AngularJS TypeScript code (yes, including my very own) where dependency injection is done in an impractical way. The most common way of doing dependency injection, is by manually injecting the dependencies while loading your AngularJS components and their accommodating TypeScript classes. What this basically means is that, while injecting a dependency, you have to do this three times (!). Not only that, all three times have to be similar in order for the injection (string matching) to work. Consider the following example:

 
angular.module("myApp", []).controller("MyController", ["$scope", "MyService", ($scope, MyService)
    => new Application.Controllers.MyController($scope, MyService)]);
module Application.Controllers {
 
    import Services = Application.Services;
 
    export class MyController {
 
        scope: any;
        myService: Services.IMyService;
         
        constructor($scope: ng.IScope, myService: Services.IMyService) {
            this.scope = $scope;
            this.myService = myService;
        }
    }
}

MyController is a class that takes in two dependencies – $scope and MyService. However, in the first code block, the injection itself is written three times (lines 1 and 2). Not only does this result in a maintenance hell, it greatly affects the readability of the code.

So, how do we solve this issue? Simple, we use AngularJS’ $inject property to do the injection in our TypeScript class. In MyController, we statically use $inject and define the dependencies like so (line 10):

module Application.Controllers {
 
    import Services = Application.Services;
 
    export class MyController {
 
        scope: any;
        myService: Services.IMyService;
        
        static $inject = ["$scope", "MyService"];

        constructor($scope: ng.IScope, myService: Services.IMyService) {
            this.scope = $scope;
            this.myService = myService;
        }
    }
}

And then simply change the wiring like so:

 
angular.module("myApp", []).controller("MyController", Application.Controllers.MyController);

Notice how elegant the wiring looks? No explicit injection that we need to worry about, all we need is to inspect the class itself to find the dependencies.

I will speak at JavaZone 2014

I’m very happy and excited to announce that I will be speaking at JavaZone 2014! If you did not know already, JavaZone is the largest IT conference in Norway. Up to 2500 software engineers and developers gather each year in Oslo during September to attend 3 days packed with presentations, lightning talks and workshops!

I will be doing a 60 minute presentation on the topic “TDD with AngularJS and TypeScript”. Make sure to book your ticket today and I will see you in September! 🙂

I will speak at the Trondheim Developer Conference

I’m thrilled to announce that I will be speaking at the Trondheim Developer Conference in October this year! If you didn’t know already, this is an awesome conference arranged once a year by technology user groups in the Trondheim area, Norway. Among the user groups behind the conference is the Norwegian .NET User Group, JavaBin Trondheim, Trondheim XP & Agile Meetup and many more!

The conference kicks off on October 27th, and the topic of my talk is “TDD with AngularJS and TypeScript”. Make sure to book your tickets today, and I will see you in October!

tdc

TypeScript Release Candidate

A release candidate version of TypeScript was finally released last week. New features have been added along the many bug fixes that were made. As of the Spring Update CTP2 for Visual Studio 2013, TypeScript is now fully supported making it a first class citizen. That means after getting the Spring Update CTP2, you won’t need to download TypeScript as a plugin to Visual Studio 2013. Notable features that have been added are simpler, more generic type declarations and order declaration merging of interfaces. Improvements to the lib.d.ts typings library have also been made, adding typings support for touch and WebGL development, making your life easier when working with HTML 5.

Generic Type System

The typing has been enhanced, making it more flexible. It is now possible to use any more freely, making type checking especially softer when working with inheritance. Consider the class Person that extends Human:

class Human {
    eyeColor: string;
}

class Person extends Human {
    eyeColor: any;
}

Giving the property eyeColor type any in the subclass was not possible prior to the RC version. Giving this possibility now, you are not forced to define the specific type found in the super class, which may be inaccessible at times. When it comes to generics, the same thing is possible. Consider the interface IPerson with a generic function and the implementing class Person:

interface IPerson<Value> {
    then<T>(f: (v: Value) => Person<T>): Person<T>;
}

class Person<Value> implements IPerson<Value> {
    then<T>(f: (v: Value) => Person<T>): Person<T>;
    then<T>(f: (v: Value) => any): Person<T> {        // This is also possible
        return undefined;
    }    
}

Declaration Merging Precedence

In addition, declaration merging of interfaces is now also possible. This makes precedence order easier when you work with external libraries. Say you have external interfaces IExternal with some functions:

interface IExternal {
    a1(): void;
    a2(): number;
}

interface IExternal {
    b1(): string;
    b2(): Date;
}

When these two interfaces are merged, they become this interface:

interface IExternal {
    b1(): string;
    b2(): Date;
    a1(): void;
    a2(): number;    
}

Notice the precedence order of the declared functions. Declaration merging is absolutely recommended, especially when you don’t want to change how the external libraries are initially referenced in your web application.

These are awesome features from the TypeScript team! I am happy that the community influenced the team to add these features, and I also would like to congratulate the team on reaching version 1.0. Well done! 🙂

I will speak at the HTML5 Developer Conference in San Francisco

I will be speaking at the HTML5 Developer Conference in San Francisco this year! I received this exciting news yesterday night at around 02:00 AM in the morning. I’m glad that I didn’t read the e-mail at that time, otherwise I wouldn’t have slept because of all the excitement! If you didn’t already know, this is the largest JavaScript and HTML5 conference in the world. It’s an awesome conference that spans one day with training sessions spanning four days in advance. The topic of my talk is titled “TDD with AngularJS and TypeScript”. I will get further details surrounding the talk eventually, whether it will be a workshop session or regular talk (or both).

Make sure you to book your tickets today, I’ll see you in ‘frisco this May! 🙂

When Two Forces Meet (AngularJS, TypeScript)

AngularJS is largely growing in popularity among front-end developers. According to a JavaScript developer survey conducted in 2013, it was shown that AngularJS was among the top two most used JavaScript frameworks. In a world where there are close to 17 million MVC JavaScript frameworks, this puts AngularJS on top of the game. On the other end of the scale, while not as widely used as AngularJS, TypeScript is slowly becoming the de facto compiler language for writing object oriented JavaScript. So what happens when these two forces meet? A great power emerges! We learned from Uncle Ben (Spider-Man movie) that with great power, comes great responsibility. In this tutorial, I show how these two forces can be combined to produce an ultimate web application.

Capture

Setup

As a .NET developer, I use Visual Studio 2013 and the TypeScript plugin for Visual Studio. This is what I recommend that you use unless you are for some reason against the Windows platform. Then using the NuGet packet manager, you can install the necessary AngularJS core files. In addition to this, make sure to install the AngularJS TypeScript definitely typed files which provides typed AngularJS components that can be used in your TypeScript code.

Bootstrapper

In AngularJS you create an app.js where you load your modules, controllers, factories and directives. You do almost the same thing in TypeScript, the only difference here is that your controllers, factories and directives are represented as TypeScript classes in an app.ts file. So your app.ts can look like this:

var appModule = angular.module("myApp", []);

appModule.controller("MyController", ["$scope", "MyService", ($scope, MyService)
    => new Application.Controllers.MyController($scope, MyService)]);

appModule.factory("MyService", ["$http", "$location", ($http, $location)
    => new Application.Services.MyService($http, $scope)]);

appModule.directive("myDirective", ()
    => new Application.Directives.MyDirective());

Note the usage of lambda, we do this to reserve lexical scope. Always make sure to use this instead of function() in TypeScript. Now that you’ve set up your bootstrapper, in the next sections we’ll look at how the individual AngularJS components are written in TypeScript.

Controller Classes

Controllers are written as classes, so your MyController.ts class can look like this:

module Application.Controllers {

    import Services = Application.Services;

    export class MyController {

        scope: any;
        myService: Services.IMyService;
	    data: any;
		
        constructor($scope: ng.IScope, myService: Services.IMyService) {
            this.scope = $scope;
            this.myService = myService;
	        this.data = [];
        }

        private GetAll() {
            this.myService.GetAll((data) => {
                this.data = data;
            });
        }
	}
}

Factory Classes

Similarly, factories or services are written as classes. So your MyService.ts class can look like this:

module Application.Services {

    export interface IMyService {
        GetAll(successCallback: Function);
    }

    export class MyService {

        http: ng.IHttpService;
        location: ng.ILocationService;

        constructor($http: ng.IHttpService, $location: ng.ILocationService) {
            this.http = $http;
            this.location = $location;
        }

        GetAll(successCallback: Function) {
            this.http.get(this.location.absUrl()).success((data, status) => {
                successCallback(data);
            }).error(error => {
                successCallback(error);
            });
        }
	}
}

Note the interface IMyService here. Always use interfaces to abstract your classes in TypeScript, just as you would usually do in a typed language.

Directive Classes

Directives are also written as classes. So your MyDirective.ts class can look like this:

module Application.Directives {

    export class MyDirective {

        constructor() {
			return this.CreateDirective();
        }

        private CreateDirective():any {
            return {
                restrict: 'E',
                template: '<div>MyDirective</div>
            };
        }
    }
}

Databinding with Alias

Finally, to be able to use your TypeScript classes from your HTML, you need to databind using alias. So your HTML can look like this:

<html data-ng-app="myApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>
<body>
	<div data-ng-controller="MyController as mc">
		<div data-ng-repeat="element in mc.data">
			<label>{{element}}</label>
		</div>
		<my-directive></my-directive>
	</div>
</body>
</html>

Databinding without Alias

Unfortunately, databinding with alias does not work in Internet Explorer 8. Neither do directive elements(!). To make it work in IE 8, you need to change your HTML so it looks like this:

<html xmlns:ng="http://angularjs.org" id="ng-app" data-ng-app="myApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!--[if lte IE 8]>
            <script>
                document.createElement('ng-include');
                document.createElement('ng-pluralize');
                document.createElement('ng-view');
                document.createElement('my-directive');
                document.createElement('ng:include');
                document.createElement('ng:pluralize');
                document.createElement('ng:view');
            </script>
            <script src="libs/es5-shim/es5-shim.js"></script>
            <script src="libs/JSON/json3.js"></script>
        <![endif]-->
</head>
<body>
	<div data-ng-controller="MyController">
		<div data-ng-repeat="element in data">
			<label>{{element}}</label>
		</div>
		<my-directive></my-directive>
	</div>
</body>
</html>

Now if you want to call your TypeScript class methods from your HTML in IE 8 without an alias, then you need to hook your methods (and everything else they use) onto the Angular scope. This can be done like the following, in MyController.ts:

module Application.Controllers {

    import Services = Application.Services;

    export class MyController {

        scope: any;
		
        constructor($scope: ng.IScope, myService: Services.IMyService) {
            this.scope = $scope;
            this.scope.myService = myService;
			this.scope.data = [];
			this.scope.GetAll = this.GetAll;
        }

        GetAll() {
            this.scope.myService.GetAll((data) => {
                this.scope.data = data;
            });
        }
	}
}

Notice how everything is hooked onto scope. That way, databinding is correctly achieved in IE 8, and you are able to call your GetAll() method from the HTML by simply typing GetAll() without alias.

Hope you enjoyed this tutorial! I’m planning on holding a workshop about this and doing TDD at this year’s Norwegian Developers Conference 2014, so make sure to book your tickets! 🙂