AngularJs in TypeScript – Services and $http

This is the 5th in a series of articles about developing for AngularJS using TypeScript. The articles in the series are:

  1. Controllers
  2. Controllers – Part 2
  3. Modules
  4. Services
  5. Services and $http (this article)
Using $http

In the previous article we added a simple MyService class which had a getPeople method that returned a static array of names. The most common type of service that I tend to write are those that use Angular’s $http service to retrieve data. When using $http I tend to make use of the get and post methods most frequently so putting together an HttpHandlerService class in TypeScript and adding methods that make it easier to use the get and post methods on the $http service would seem to be useful.

To do this we can add the following code to the KodeYak module in the service.ts file:

  export class HttpHandlerService extends Service
  {
    httpService: ng.IHttpService;
    handlerUrl: string;

    constructor( $http: ng.IHttpService )
    {
      super();
      this.httpService = $http;
    }

    useGetHandler( params: any ): ng.IPromise< any >
    {
      var result: ng.IPromise< any > = this.httpService.get( this.handlerUrl, params )
        .then( ( response: any ): ng.IPromise< any > => this.handlerResponded( response, params ) );
      return result;
    }

    usePostHandler( params: any ): ng.IPromise< any >
    {
      var result: ng.IPromise< any >  = this.httpService.post( this.handlerUrl, params )
        .then( ( response: any ): ng.IPromise< any > => this.handlerResponded( response, params ) );
      return result;
    }

    handlerResponded( response: any, params: any ): any
    {
      response.data.requestParams = params;
      return response.data;
    }

  } // HttpHandlerService class

The definition of the HttpHandlerService class has 2 properties:

  1. httpService – a pointer to the AngularJS $http service (which will be injected via dependency injection)
  2. handlerUrl – the url that will be used to get/post data

It also has 3 methods:

  1. useGetHandler – This will call the handlerUrl and use the get method on the $http service to get data
  2. usePostHandler – This will call the handlerUrl and use the post method on the $http service to post data
  3. handlerResponded – This will be called when the get/post methods of the $http service respond and it will add the request parameters to the response. The response will happen asynchronously so it can be useful to know what the request parameters were when a repsonse is received
Backend Handler

Before we create a concrete service class (based on the HttpHandlerSevice class we just created above) we need to create a backend handler that the service can call. One way to do this is to add a Generic Handler to your Visual Studio project and use that as your backend.

I added a new handler, called PeopleHandler, into a new Handlers folder of my project and updated it to look like the following:

  public class PeopleHandler : IHttpHandler
  {

    public bool IsReusable
    {
      get
      {
        return false;
      }
    }

    public void ProcessRequest( HttpContext context )
    {
      context.Response.ContentType = "text/plain";
      context.Response.Write( "Hello People" );
    }

  } // PeopleHandler class
Service Implementation

We can now add a new service class, called PeopleService, which extends HttpHandlerService and makes use of the PeopleHandler to get some data. To do this we add the following code to the MyTestApp module section of the service.ts file:

  export class PeopleService extends KodeYak.HttpHandlerService
  {
    static $inject = ['$http'];

    constructor( $http: ng.IHttpService )
    {
      this.handlerUrl = 'Handlers/PeopleHandler.ashx';
      super( $http );
    }

    getPeople(): ng.IPromise< any >
    {
      var config: any = {};
      return this.useGetHandler( config );
    }

  } // PeopleService class

The getPeopleMessage method sets up an empty object, called config, and passes this to the useGetHandler method. As we define the url for our handler in the constructor this means that calling getPeopleMessage will call out to our handler and then asynchronously receive the response.

Using the Service

We now need to update our controller (the MyController class) in the controller.ts file so that the constructor now looks like the following:

    static $inject = ['$scope', 'myService', 'peopleService'];

    constructor( $scope: IMyScope, service: MyService, peopleService: PeopleService )
    {
      super( $scope );
      $scope.message = { title: 'Hello World!!' };

      $scope.people = service.getPeople();

      peopleService.getPeopleMessage()
        .then( ( data ) => $scope.message.title = data );
    }

The last line in the constructor is of primary interest as this is the call to our new service. As you can see it calls the service methods and follows that with a call to the .then method. This is because our service is returning a promise and the .then method will only be called when the service receives the response from the handler. Once the handler returns the data it will be fed through and will feed through to the lambda expression:

  ( data ) => $scope.message.title = data

This is TypeScript notation for a lamba expresion (sometimes referred to as an arrow function) which is effectively storing the context of the method call so that when it is called (remember it’s going to be triggered asynchronously) the context is the same (we could use this within the lambda expression and it would still work).

Our lambda expression is saying that the response from calling our service method will return a single value, and we will then attach that value to the message.title property on the $scope.

In Action

What you should see if you build the project and view the page is that the Hello World message displays with the list of people’s names below it. After a short delay the Hello World message will change into a Hello People message as this is the response from the PoepleHandler.

If you refresh the page again you probably won’t even see the Hello World message as the first time it was run the PeopleHandler had to be initialised but subsequent calls go through almost instantly.

Conclusion

We now have a base class for services which use the HTTP GET and POST verbs and have added simple service that builds on that.

In the next article I will extend the handler so that it can be used to get different types of data.

AngularJS in TypeScript – Services

This is the 4th in a series of articles about developing for AngularJS using TypeScript. The articles in the series are:

  1. Controllers
  2. Controllers – Part 2
  3. Modules
  4. Services (this article)
  5. Services and $http
Services

When writing AngularJS services in JavaScript the most common style is to register a function which contains other functions and properties, like the following:

  myApp.service( 'myService', 
    function()
    {
      this.getMessage = 
        function()
        {
          return 'Hello World';
        }
    } );

This is very easy to convert to TypeScript as it’s equivalent to a class with methods and properties:

  class MyService
  {
    getMessage(): string
    {
      return 'Hello World';
    }
  }

  myApp.addService( 'myService', MyService );

As you can see from the above code we defined our service class and then added it to the module/app. In the previous articles we defined our module to be based on our Module class which doesn’t have an addService method, so we’ll have to add that first. The app.ts file would now be as follows:

module KodeYak
{
  export class Module
  {
    app: ng.IModule;

    constructor( name: string, modules: Array< string > )
    {
      this.app = angular.module( name, modules );
    }

    addController( name: string, controller: Function ): void
    {
      this.app.controller( name, controller );
    }

    addService( name: string, service: Function ): void
    {
      this.app.service( name, service );
    }

  } // Module class

}
Simple Service

First of all add a new file to your project, called service.ts, and update the html file to load it by updating the script loading in the <head> tag to look like the following:

  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
  <script src="scripts/service.js"></script>
  <script src="scripts/controller.js"></script>
  <script src="scripts/app.js"></script>

(The service is loaded first so that it can be used by the controller and added to the module)

Then we can add the following code to the service.ts file:

module KodeYak
{
  export class Service
  {

  } // Service class

}

This code defines a new Service base class, which is empty as we don’t currently have anything to be added at that level. It’s probably a good idea to define this class though as we may need to have some functionality common to all our services and it could easily be added here.

At the bottom of the service.ts file we can then add the following code which will create a simple service that has a getPeople method which returns an array of people’s names:

module MyTestApp
{
  export interface IPerson
  {
    name: string;
  }

  export class MyService extends KodeYak.Service
  {
    getPeople(): Array< IPerson >
    {
      return [
        { name: 'John Smith' },
        { name: 'Sam Smith' },
        { name: 'Bob Smith' },
        { name: 'Delia Smith' }
      ];
    }

  } // MyService class

}

We then need to update our app.ts file so that the new service is included in the module:

  var myApp: KodeYak.Module = new KodeYak.Module( 'myTestApp', [] );
  myApp.addController( 'myController', MyController );
  myApp.addService( 'myService', MyService );

Now we can update our controller so that our new service is injected into the controller and the controller can use it to retrieve the people data. We also need to update the IMyScope interface to have a people property. The MyController code in the controller.ts file should be updated to look like the following:

module MyTestApp
{
  export interface IMyMessage
  {
    title: string;
  } // IMyMessage interface

  export interface IMyScope extends KodeYak.IScope
  {
    message: IMyMessage;
    people: Array< IPerson >;
  } // IMyScope interface

  export class MyController extends KodeYak.Controller
  {
    scope: IMyScope;

    static $inject = ['$scope', 'myService'];

    constructor( $scope: IMyScope, service: MyService )
    {
      super( $scope );
      $scope.message = { title: 'Hello World!!' };

      $scope.people = service.getPeople();
    }

    clickMe(): void
    {
      alert( this.scope.message.title );
    }

  } // MyController class

}

and we can update the code in the body of the html page so that it will display the names of the people to be as follows:

  <div ng-app="myTestApp" ng-controller="myController">
    <h1>{{message.title}}</h1>

    <ul>
      <li ng-repeat="person in people">{{person.name}}</li>
    </ul>
  </div>

The code above added an ng-repeat loop which added a list item (li) tag for each item in the people list and within each li tag it is displaying the name property from the object.

If you now build the project and refresh your page you should see the Hello World message and below that the list of people returned by the service.

Conclusion

We now have a basic service in our project and in the next article I plan to build on this by creating a more complex service which makes use of the AngularJS $http service.

Slight Detour

It’s been a couple of months since my last post as a number of things have happened that meant I didn’t have time to deal with this blog. Now that things are starting to get back to normal I’ve got a bit more time on my hands again and have been thinking about my next blog post.

I need to pick up on the AngularJS in TypeScript series and add the next article but in the last couple of weeks I’ve been sidetracked on to another project.

Navigation

I do a lot of my development work in Visual Studio and use a number of extensions to get the environment working in a way that I feel makes me most productive. One of these tools is CodeMaid which has some excellent code formatting tools but it’s the code digging functionality (via the CodeMaid Spade tool window). This tool displays a structural view of C# code that allows you to easily find methods, properties etc. and navigate to them by double clicking on them. I used it a lot but as I do a lot of coding in JavaScript and TypeScript I wanted a tool to do the same thing for those languages too.

I did look for existing extensions and found a JavaScript Parser extension, which works well for JavaScript but doesn’t handle TypeScript. In light of this I decided to start writing my own extension.

Code Trees

The first thing I had to consider was how to get a syntax tree for TypeScript and the first thing that sprung to mind was that the TypeScript compiler was open source so why not look into that? Thankfully it wasn’t too difficult to get the TypeScript source code and then found that TypeScript has a Parser class which return a StyntaxTree – exactly what I needed. The code to run the parser is as follows:

  var syntaxTree = TypeScript.Parser.parse( 'dummy.ts', codeToParse, false, options );

So now I had some JavaScript code that could generate a syntax tree for TypeScript files but I needed to be able to trigger this and deal with the results from within my Visual Studio extension (C# .NET code). After a bit more research I stumbled across the ClearScript project which sounded like it would fit the bill perfectly.

I added ClearScript to my project (via a NuGet package) and then was able to trigger some JavaScript and retrieve the results all from within my C# code. It needed a lot work, particularly around deciding what processing would be done in JavaScript and what would then be picked up from the C# code, but the seeds were there.

Another advantage to using the TypeScript parser is that it has to handle JavaScript parsing as well, since TypeScript is a superset of JavaScript, so I should be able to use the same process for generating code structures for TypeScript and JavaScript files.

Different Languages

As the only real objective for my extension is to allow simple structural navigation of code files then it makes sense to cater for as many file types as possible. The initial code was written to cater for TypeScript and JavaScript files but since Visual Studio already provides information about the code structure for C# and C++ files then it makes sense to handle those as well.

In future it should be possible to also handle XML files, html files and other structured code blocks so the model has to be simple enough and adaptable enough to handle such additions.

Progress

As it currently stands I have a (mostly) functional extension which currently handles TypeScript, JavaScript, C# and C++ files. It’s not quite ready for wider release as I need to tidy up the handling of some elements (delegates for one) but I am aiming to release it in the coming months and, once I’ve tidied the code, I hope to make it open source and see where it goes from there.

KodeTree extension

KodeTree extension

I also intend to post further articles which may discuss some of the more detailed design decisions and hurdles that I have encountered (and will encounter) during this development.

Until then…

AngularJS in TypeScript – Modules

This is the 3rd in a series of articles about developing for AngularJS using TypeScript. The articles in the series are:

  1. Controllers
  2. Controllers – Part 2
  3. Modules (this article)
  4. Services
  5. Services and $http
Modules

In my first post on controllers (see above for link) the html code at the end of the article looked like the following:

  <div ng-app="" ng-controller="MyTestApp.MyController">
    <h1>{{message.title}}</h1>
  </div>

You’ll notice that the ng-app attribute is just an empty string and we have to reference our controller class explicitly (module name and class name). The ng-app attribute is used to define the core application module that will define the structure of the AngularJS project within the bounds of the element it’s contained in (the div element in our case).

So now we want to define our AngularJS module and attach our controller to it. To do that in JavaScript we could include another script to our html file, called app.js (after the line that includes controller.js) and in it add the following code:

var myApp = angular.module( 'myTestApp', [] );

myApp.controller( 'myController', MyTestApp.MyController );

Then we need to update our html to use myTestApp in the ng-app attribute and update our ng-controller attribute to point to myController (note the lowercase m as we’re now referencing the name that was registered with the module not the function).

...
  <script src="scripts/controller.js"></script>
  <script src="scripts/app.js"></script>
...
  <div ng-app="myTestApp" ng-controller="myController">
    <h1>{{message.title}}</h1>
  </div>

Now if we refresh our page we still see the Hello World!! message.

Converting to TypeScript

The next step is to put together some (re-usable) code in TypeScript that will allow us to define a module and to add artefacts to it (so far we are only adding a controller but will in future want to add services, constants etc.) First of all we need to create a new TypeScript file, called app.ts, and then delete the app.js (it will be generated from our app.ts file). Add the following code to the app.ts file:

module KodeYak
{
  export class Module
  {
    app: ng.IModule;

    constructor( name: string, modules: Array< string > )
    {
      this.app = angular.module( name, modules );
    }

    addController( name: string, controller: Function )
    {
      this.app.controller( name, controller );
    }
  }
}

Then we can rewrite our JavaScript with the following TypeScript (you can just add it to the app.ts file, below the code you just added):

module MyTestApp
{
  var myApp = new KodeYak.Module( 'myTestApp', [] );
  myApp.addController( 'myController', MyController );
}

Saving all the files and refreshing our page should show the amazing Hello World!! message.

Benefits

So what are the benefits in using our own Module class? The TypeScript code that we ended up with was very similar to the JavaScript code but we now have the ability to add some common configuration, services, constants or routing to our Module class (or a sub-class) and those will be available to us wherever we use it. We also have access to the original Angular module (through myApp.app) if we ever need it.

Conclusion

We now have a (very) basic Module class that we can add controllers to and in future articles I will expand this class so that it will work with services, constants and other AngularJS concepts.

AngularJS via TypeScript – Controllers Pt2

This is the 2nd in a series of articles about developing for AngularJS using TypeScript. The articles in the series are:

  1. Controllers
  2. Controllers – Part 2 (this article)
  3. Modules
  4. Services
  5. Services and $http
References

In my previous post on AngularJS via TypeScript – Controllers I forgot to mention a couple of things.

In my code examples I didn’t include any references but I was referring to an external type (one I didn’t declare in the code), namely ng.IScope. In previous versions of the TypeScript tooling (I use Visual Studio as my development environment) you had to explicitly declare references at the top of your TypeScript files to let the compiler know where it should look to find the definitions for types not defined in the current file. These references would look like the following:

/// <reference path="typings/angularjs/angular.d.ts" />

The reference above is telling the compiler to look in the typings/angularjs folder for a definition file (hence the .d.ts extension) called angular.d.ts.

Since a project like AngularJS is not actually written in TypeScript, but written in JavaScript, where do we get these definitions? Thankfully there is a community of people putting these together. The definition files contain information about the classes, interfaces, methods and properties that are available in the JavaScript code so that the TypeScript compiler can use that information to check that our code is valid. (The definition files just contain the signatures of these classes, methods etc. not their implementation, that is still in the original JavaScript files).

One of the best places to get these definition files is on Boris Yankov’s Definitely Typed GitHub site. These can also be added to your Visual Studio project via nuget packages.

I have found that in the latest version of the TypeScript tooling (v0.9.5) and when using it in Visual Studio Express 2013 for Web (yes, you can develop these projects in the free version of VS) there is no need to declare the explicit references as it will automatically pick up and refer to all the TypeScript files included in the project.

Minification and Dependency Injection

As I mentioned in the previous post the $scope is passed to the controller via Angular’s dependency injection (DI). In the code I posted, the DI engine knows what needs to be passed in based on the name of the parameter, $scope. This is fine for the code I posted but what happens if the code is minified? The name of this parameter will likely be reduced and the DI engine will no longer be able to work out what needs to be passed in.

To get around this, Angular allows us to define an $inject property which contains an array of strings to represent what objects are to be injected. In plain JavaScript this is done by adding a $inject property to the controller function, which was called MyController in our case:

  MyController['$inject'] = ['$scope'];

The code above tells the DI engine that when creating an instance of MyController it needs to pass $scope as it’s only parameter.

This is fairly easy to replicate in TypeScript as we just need to add a static property to our MyController class:

  static $inject = ['$scope'];

I tend to put that line just above the constructor as if I need to change the list of parameters being passed into the controller then I also need to update the strings in the array. (The order of the items is just as important as the names).

Conclusion

Hopefully that clears up the creation of controllers for AngularJS using TypeScript and we can now move on to the next AngularJS artefact – modules.

AngularJS via TypeScript – Controllers

This is the 1st in a series of articles about developing for AngularJS using TypeScript. The articles in the series are:

  1. Controllers (this article)
  2. Controllers – Part 2
  3. Modules
  4. Services
  5. Services and $http
Introduction

As I mentioned in my previous post I am currently using AngularJS a lot at the moment and am trying to write the majority of my JavaScript code using TypeScript. To be able to do this effectively I wanted to put together a set of base classes in TypeScript that I could use in my AngularJS projects.

A lot of simple AngularJS demos on the web seem to start by just creating a controller so I’m going to do the same here. Let’s take a simple example of an AngularJS controller written in JavaScript:

function MyController( $scope )
{
  $scope.message = { title: &quot;Hello World!!&quot; };
}

This could then be saved in a file called controller.js and then used in a web page like the following:

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
 &lt;title&gt;AngularJS in TypeScript&lt;/title&gt;
 &lt;script type=&quot;text/javascript&quot; src=&quot;http://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js&quot;&gt;&lt;/script&gt;
 &lt;script type=&quot;text/javascript&quot; src=&quot;controller.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;div ng-app=&quot;&quot; ng-controller=&quot;MyController&quot;&gt;
 &lt;h1&gt;{{message.title}}&lt;/h1&gt;
&lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;

Which would then output something like the following:

Hello World!!

As you can see it’s a very simple and trivial AngularJS example and one that shouldn’t be difficult to write using TypeScript. The first thing we have to do is delete our controller.js file and create a new file, called controller.ts. We can then populate controller.ts with the following code:

class MyController
{
  constructor( $scope )
  {
    $scope.message = { title: &quot;Hello World!!&quot; };
  }
}

When compiled this would produce our controller.js with the following JavaScript:

var MyController = (function () {
    function MyController($scope) {
        $scope.message = { title: &quot;Hello World!!&quot; };
    }
    return MyController;
})();

and if you refresh the page you see the same Hello World!! text. Wow! I bet you’re amazed with that eh? Nope?

Adding Types

All we’ve done is prove we can write some TypeScript which creates a simple controller but doesn’t really show why we’d want to use TypeScript in the first place. One of the useful features when writing TypeScript is the code-completion help that you get but to get proper benefit from that you have to be explicit with types. In the example above we passed a $scope property to the constructor but didn’t specify a type so would get no help with the methods and properties available to us.

If we now change the code in controller.ts to be as follows:

interface IMyMessage
{
  title: string;
}

interface IMyScope extends ng.IScope
{
  message: IMyMessage;
}

class MyController
{
  constructor( $scope: IMyScope )
  {
    $scope.message = { title: &quot;Hello World!!&quot; };
  }
}

You can see above that our $scope parameter in the constructor has an explicit type, IMyScope and that is defined to inherit from ng.IScope (this is an interface representing the properties and methods available on an AngularJS $scope). The IMyScope type has a message property which itself is of type IMyMessage, where IMyMessage has a string property called title. If you now recompile controller.ts it will produce exactly the same JavaScript in controller.js as it did before.

That’s because all we added were type definitions which are not relevant to the JavaScript output but are useful for us when editing the code. So we’re writing extra code just so we can get some better code-completion then? So far, yes, but if we extend it a bit further we will begin to see other benefits.

Triggering Events

If we now change our web page and add a button below the h1 element:

...
&lt;div ng-app=&quot;&quot; ng-controller=&quot;MyController&quot;&gt;
  &lt;h1&gt;{{message.title}}&lt;/h1&gt;
  &lt;button ng-click=&quot;clickMe()&quot;&gt;Do It!&lt;/button&gt;
&lt;/div&gt;
...

The standard thing to do next would be to change the controller so that it adds a method called clickMe to the scope, like the following:

...
class MyController
{
  constructor( $scope: IMyScope )
  {
    $scope.message = { title: &quot;Hello World!!&quot; };

    $scope.clickMe = function()
    {
      alert( &quot;Hello&quot; );
    };
  }
}

Then clicking on the button will show an alert dialog with the Hello text in it.

Personally I’m not a fan of these inline functions at the best of times but even more so when writing in TypeScript. Instead I’d like to write a proper method and have that called by the click event. Since the $scope is provided to my controller through the AngularJS dependency injection pattern it’s not a trivial matter to add a clickMe method to it. It is, however, easy to add a new method to my controller and I could store a reference to my controller on the scope so that the view/html can get access to the method.

To do this I could change my controller to look like the following:

...
class MyController
{
  constructor( $scope: IMyScope )
  {
    $scope.events  = this;
    $scope.message = { title: &quot;Hello World!!&quot; };
  }

  clickMe()
  {
    alert( &quot;Hello&quot; );
  }
}

Then the button in my html code could be updated to the following:

...
  &lt;button ng-click=&quot;events.clickMe()&quot;&gt;Do It!&lt;/button&gt;
...
Referencing $scope

Now, what if I wanted to display the message.title property from the $scope in my alert box when the button is clicked? To do this I’d need to store a reference to my $scope so that the clickMe method get to it. This can be done as follows:

...
class MyController
{
  scope: IMyScope;

  constructor( $scope: IMyScope )
  {
    this.scope     = $scope;
    $scope.events  = this;
    $scope.message = { title: &quot;Hello World!!&quot; };
  }

  clickMe()
  {
    alert( this.scope.message.title );
  }
}
Code Reuse and Inheritance

For me the first 2 lines of the constructor seem like common things that I’d like to have on all my controllers but I don’t really want to have to add them every time. This is where TypeScript really comes into it’s own for me – inheritance. I can now write a base controller class like the following:

module KodeYak
{
  export interface IScope extends ng.IScope
  {
    events: Controller;  
  }

  export class Controller
  {
    scope: IScope;

    constructor( $scope: IScope )
    {
      this.scope        = $scope;
      this.scope.events = this;
    }
  }
}

and I can change the MyController class to the following:

module MyTestApp
{
  export interface IMyMessage
  {
    title: string;
  }

  export interface IMyScope extends KodeYak.IScope
  {
    message: IMyMessage;
  }

  export class MyController extends KodeYak.Controller
  {
    scope: IMyScope;

    constructor( $scope: IMyScope )
    {
      super( $scope );
      $scope.message = { title: &quot;Hello World!!&quot; };
    }

    clickMe()
    {
      alert( this.scope.message.title );
    }
  }
}

I added use of TypeScript modules to the code above so as to namespace the code to prevent similar class names from interfering with each other. (This means that the ng-controller tag in the html file should be changed to MyTestApp.MyController)

Conclusion

Hopefully in this post I’ve started to show the merits of using TypeScript to write AngularJS applications and in future posts I intend to expand on this with the intention of putting together a library of TypeScript classes that can be used to make AngularJS application even easier to develop!

Evolution of a JavaScript Developer

I have been writing applications with JavaScript for well over a decade but it’s only in the last year or so that I’ve started to consider it as ‘proper development’. Whilst a number of these applications would contain thousands of lines of JavaScript, the approach and structure of this code was not at a level that could be considered professional.

Whilst the back end code would be written in an object-oriented language (mainly C# these days but also Java and Turbo Pascal in days gone by) and approached with a good amount of analysis and design, the front end scripting (another term which suggests a lower level of programming) would tend to merit a lot less attention to detail.

I have developed a number of libraries and components in JavaScript over the years but it wasn’t until jQuery came along that I started to look at what other people were doing with the language. I embraced jQuery in a big way and it formed a core part of the JavaScript code I wrote for the next few years.

Whilst it did make interactions with the DOM much easier and reduced the amount of code that was written for each application, using jQuery didn’t really encourage a more structured approach to JavaScript coding.

I started to hear about TypeScript towards the end of 2012 but dismissed originally as I perceived that it would be an overhead to development and wouldn’t really bring any benefits. Early in 2013 I was about to start work on a new project and decided to give TypeScript a chance, mainly because it was being driven by Anders Hejlsberg who was also instrumental in the emergence of Turbo Pascal and C#.

I began to see benefits almost immediately as TypeScript is effectively a superset of the JavaScript language. You can write TypeScript code that is pure JavaScript but it’s when you start to incorporate the more object-oriented elements (such as module and class) along with proper type definitions that you start to see a noticeable return.

Whilst it is possible to to create classes with namespacing and inheritance in vanilla JavaScript, it’s not something that is easy to do or nicely structured for future maintenance. TypeScript makes it much easier to develop structured modules/namespaces, classes and make good use of inheritance to create JavaScript code that is cleaner, more maintainable and, generally, more thoughtfully designed. (Most of the features in TypeScript emulate elements from the upcoming ECMAScript 6 specification but it makes it possible to use these in code today)

Last summer I was introduced to the next framework which had a major impact on the way I developed applications for the web. This framework was AngularJS which brings an MVC style approach to client side development. I had tried KnockoutJS for its data-binding a few years before but found it slowed the application down if numerous fields were bound at the same time and since data-binding was it’s raison d’être I quickly dropped it. The data-binding is only one string in the AngularJS bow but it was light years ahead of the experience I had found with KnockoutJS (the JavaScript engines in most modern browsers have come on leaps and bounds too which almost certainly helped!).

A lot of articles on AngularJS write about the data binding or the dependency injection but it’s the use of directives that I find to be its biggest game changer. Being able to properly separate the DOM manipulation from the operational part of the code is another step towards considering JavaScript as a grown up and professional programming language, not just a scripting language that helps tidy up the UI.

This article is very dry (sorry!) without any code samples as it’s intended to give a background on my experiences and how I currently see the JavaScript development scene. In future articles I intend to look at specific problems I have encountered and possible solutions to overcome them, particularly developing for AngularJS and making good use of TypeScript.