TypeScript : Using Backbone.Marionette and REST WebAPI (Part 1)

This article ( Part 1 and Part 2) aims to walk the reader through setting up a Backbone.Marionette SPA application with Visual Studio 2013, and in particular, write Marionette JavaScript using TypeScript.  Generally, writing JavaScript applications relies on RESTful web services, so this blog will also aim to show how to accomplish this with ASP.NET WebAPI data controllers.

Backbone.Marionette was designed to simplify large scale JavaScript applications.  After a mate of mine ( three votes, two votes, two votes one. ) loaned me a book on Marionette, I decided to give it a whirl.

Being the unit-test junkie that I am, I also aim to show how to build JasmineJs unit-tests to test your REST services, and also show how to generate and use nested JSON objects.  Nested JSON data fits hand in glove with Backbone Models and TypeScript.

Update : Many thanks to Alastair who pointed out some typos. These have now been fixed.

Firstly, a few links:

Backbone.Marionette.js: A gentle introduction is an excellent book by David Sulc, that I used to gently introduce me to Marionette. 

Marionettejs.com is the official Marionette site – downloads and documentation.

MarionetteJS 1.4.1 on nuget is the nuGet repository by benb1in.

marionette.TypeScript.DefinitelyTyped is the nuGet repository for TypeScript definitions by Jason Jarrett

DefinitelyTyped/marionette holds the TypeScript definition .d.ts files for Marionette, by sventschui.

Twitter.Bootstrap is the nuGet repository for Bootstrap 3.0.1.1 by Jakob Thornton and Mark Otto

bootstrap.TypeScript.DefinitelyTyped is the nuGet repository for TypeScript definitions of boostrap by Jason Jarrett

As always, the full source code for this article can be found on github: blorkfish/typescript-marionette

I have broken this article up over two parts, as we will be covering quite a few techniques and sample code – but fear not, it is quite fast-paced with tangible results every step of the way.  As an overview, we will accomplish the following:

  • Setting up a Visual Studio 2013 project.
  • Install required nuGet packages.
  • Creating the ASP.NET HomeController and View.
  • Including required javascript libraries in our Index.cshtml.
  • Creating a Marionette.Application.
  • Adding a Marionette Region
  • Referencing the Region in the Application
  • Creating a Marionette.View
  • Using bootstrap to create a clickable NavBar Button
  • Using Backbone Models to drive NavBar buttons.
  • Creating a Backbone.Collection to hold multiple Models
  • Creating a Marionette.CompositeView to render collections
  • Rendering Model Properties in templates
  • Using Marionette Events.
    At the end of Part 1, our awesome application will look like this : and use events to notify our App when a navbar button is clicked:

image

image

In Part 2 of this article we will cover the following:

    • Creating an ASP.NET WebAPI Data Controller.
    • Unit testing the WebAPI Data Controller in C#
    • Modifying the WebAPI Data Controller to return a collection of nested C# POCO objects.
    • Defining TypeScript Backbone.Model classes to match our nested class structure.
    • Writing Jasmine unit tests for our Backbone Collection.
    • Creating a Marionette.CompositeView to render data in a bootstrap table.
    • Using a Marionette.CompositeView as an ItemView
    • Rendering nested Backbone.Collections
    • Using CompositeView properties to generate html.
    • Using bootstrap styles in a Marionette.CompositeView
    When we are complete with this tutorial, we will have generated a nested Json structure as follows: UserList –> User –> RoundScores –> RoundScore.
    We will then render it as follows:

image

 

Setting up a Visual Studio 2013 project.

Firstly, let’s create a new Visual Studio project.  Make sure that you select an ASP.NET MVC 4 Web Application.  This will allow for the addition of WebAPI data controllers.

image

Personally, I prefer creating an Empty web application – as Visual Studio makes it very easy to add Controllers and Views later.  Change the View Engine to Razor.

image

Next, let’s switch to the .NET framework 4.5.1.  Right-click on the project and choose Properties.  Under Application, change the Target framework to .NET Framework 4.5.1:

image

Install required nuGet packages.

Next, install the following nuGet packages.  Click on TOOLS | Library Package Manager | Package Manager Console, and type the following:

Install-Package Backbone.Marionette

Install-Package marionette.TypeScript.DefinitelyTyped

Install-Package jasmine-js

Install-Package jasmine.TypeScript.DefinitelyTyped

Install-Package Twitter.Bootstrap

Install-Package bootstrap.TypeScript.DefinitelyTyped

Install-Package jasmine-jquery.TypeScript.DefinitelyTyped

Install-Package json2

Install-Package Newtonsoft.Json

Install-Package Microsoft.AspNet.WebApi

Install-Package underscore.TypeScript.DefinitelyTyped

NOTE : Compiling the project now will generate about 120 compile errors, similar to the following:

Build: Duplicate identifier ‘abort’. Additional locations

To fix this, navigate to the Scripts / typings / jasmine directory, and delete the jasmine-1.3.d.ts file from the project.

Creating the ASP.NET Home Controller and View.

Next, we will need to create a Controller and View to serve up a simple web page.

From Solution Explorer, right-click on the Controllers directory, and select Add | Controller.  Call it HomeController, and use the Empty MVC Controler Template:

image

Now create a Home directory under Views – and then right-click on the Home directory, and select Add | View .  Name the View “Index” as below:

image

Our solution explorer should look as follows:

image

Modify the Index.cshtml with some Hello world text as follows – just to check that we can hit this view:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        <h1>Hello Home Controller</h1>
    </div>
</body>
</html>

Running the application now ( hit F5 ) should successfully run the HomeController, and serve our Index.cshtml page:

image

Including required javascript libraries in our Index.cshtml.

Our next step is to reference some of the javascript libaries that we downloaded via nuGet in order for Marionette to work correctly.  Note that nuGet has placed the downloaded javascript libaries in the folder /Scripts – and the downloaded TypeScript definition files in /Scripts/typings.

Also, when running with Internet Explorer, we will need to ensure that IE uses the correct engine when parsing both the DOM and JavaScript.  This is accomplished by adding a meta tag to the page to force IE to use the latest JavaScript engine (by default, IE will revert to the IE 8 engine).

Modify the Index.cshtml page to include the following javascript libaries – and add the meta tag for IE as follows:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Index</title>

    <link rel="stylesheet" href="../../Content/bootstrap.css" type="text/css" />

    <script language="javascript" type="text/javascript" src="../../Scripts/jquery-1.9.1.js"></script>
    <script language="javascript" type="text/javascript" src="../../Scripts/json2.js"></script>
    <script language="javascript" type="text/javascript" src="../../Scripts/underscore.js"></script>
    <script language="javascript" type="text/javascript" src="../../Scripts/backbone.js"></script>
    <script language="javascript" type="text/javascript" src="../../Scripts/backbone.marionette.js"></script>
    <script language="javascript" type="text/javascript" src="../../Scripts/bootstrap.js"></script>
    
</head>
<body>
    <div>
        <h1>Hello Home Controller</h1>
    </div>
</body>
</html>

Creating a Marionette.Application

All Marionette SPAs start with a Marionette.Application.  The Marionette.Application has a number of responsibilities, including responding to application-wide events, and defining broad html “regions” that relate to specific application controllers and views.

To create a Marionette Application, simply create a class that extends from Marionette.Application.

This is one of the greatest advantages of using Backbone and Marionette with TypeScript.  The TypeScript extends keyword does exactly what you would expect it to do – it extends the definition of an existing class.  Just what you would expect from an Object Oriented language.  Unfortunately, most of the popular JavaScript libraries are not built this way, and use configuration settings to drive object behaviour.  Coming from a strongly typed background, I personally find it easier to understand and work with Backbone and Marionette because of this.

I plan to write a blog fairly soon comparing how Backbone, ExtJs, AngularJs and Marionette shape up as compatible libraries when using TypeScript and Visual Studio as your main development tools.  In the  meantime, though, Marionette wins the race hands-down (IMHO).

So back to the task at hand.  I prefer to keep all TypeScript code in a separate directory, named /tscode. Go ahead and create this directory, and then create a new TypeScript file in the /tscode directory named MarionetteApp.ts:

Add | New Item | Visual C# | Web | TypeScript File:

/// <reference path="../Scripts/typings/jquery/jquery.d.ts"/>
/// <reference path="../Scripts/typings/underscore/underscore.d.ts"/>
/// <reference path="../Scripts/typings/backbone/backbone.d.ts"/>
/// <reference path="../Scripts/typings/marionette/marionette.d.ts"/>

class MarionetteApp extends Marionette.Application {
    constructor() {
        super();
        this.on("initialize:after", this.initializeAfter);
    }
    initializeAfter() {
        alert("initializeAfter called");
    }
}

Now, lets include this file in the Index.cshtml.  Note that to start-up a Marionette application, we need to instantiate an instance of our Marionette.Application, and call the start() function:

Modify your index.cshtml file – firstly to include the MarionettApp.js file in the <head> element, and then with a script down the bottom to instatiate the application, and call start() :

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Index</title>

    <link rel="stylesheet" href="../../Content/bootstrap.css" type="text/css" />

    <script language="javascript" type="text/javascript" src="../../Scripts/jquery-1.9.1.js"></script>
    <script language="javascript" type="text/javascript" src="../../Scripts/json2.js"></script>
    <script language="javascript" type="text/javascript" src="../../Scripts/underscore.js"></script>
    <script language="javascript" type="text/javascript" src="../../Scripts/backbone.js"></script>
    <script language="javascript" type="text/javascript" src="../../Scripts/backbone.marionette.js"></script>
    <script language="javascript" type="text/javascript" src="../../Scripts/bootstrap.js"></script>
    
    <script language="javascript" type="text/javascript" src="../../tscode/MarionetteApp.js"></script>
</head>
    <body>
        <div>
            <h1>Hello Home Controller</h1>
        </div>

        <script type="text/javascript">
            var marionetteApp = new MarionetteApp();
            marionetteApp.start();
        </script>
    </body>
</html>

Running the web application now should call the alert() function :

image

Adding a Marionette Region

As mentioned before, one of the responsibilities of  a Marionette Application is to create and manage regions.  Think of a region as a broad section of your html that Marionette will inject DOM elements into.  These regions can be shown and hidden – and can even transition with JQuery animations.  To create a Region, simply add a div to your html page, and specify an id.   As we have already installed bootstrap with nuGet, let’s use it to create a navbar panel with a region in it. 

Modify your Index.cshtml as follows:

 <body>
        
        <div class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="row">
                    <div class="col-lg-6">
                        <div >TypeScript Marionette</div>
                    </div>
                    <div class="col-lg-6">
                        <div id="navbarRegion" >
                            <p>navbarRegion</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>        
        
        <div class="row">
            <div class="col-lg-12">
                <h1>Hello Home Controller</h1>    
            </div>
        </div>        

        <script type="text/javascript">
            var marionetteApp = new MarionetteApp();
            marionetteApp.start();
        </script>
    </body>

Note that we are starting to use some bootstrap styles here – creating a navbar, containers and rows.

Unfortunately, running the app now will produce a dark navbar, with the navbar text very difficult to read, as well as overlapping our Hello Home Controller Text:

image

To fix this, create an app.css file in the /Content directory, with the following styles:

body { 
   padding-top : 60px; 
 } 

.app-navbar-text { 
   Font-family : Verdana,Arial,Sans-serif; 
   Font-size : 25px; 
   Font-style : Normal; 
   color : White; 
   padding-top : 5px; 
 } 

Now include this app.css in the Index.cshtml file:

    <link rel="stylesheet" href="../../Content/bootstrap.css" type="text/css" />
    <link rel="stylesheet" href="../../Content/app.css" type="text/css" />

And finally apply the app-navbar-text style to the divs in the navbar:

        <div class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="row">
                    <div class="col-lg-6">
                        <div class="app-navbar-text">TypeScript Marionette</div>
                    </div>
                    <div class="col-lg-6">
                        <div id="navbarRegion" class="app-navbar-text">
                            <p>navbarRegion</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>        

Your page should now at least be readable:

image

Referencing the Region in the Application

To reference an html div as a Region in Marionette, we simply need to call the Marionette.Application function addRegions().  As this function is at the Application level, the easiest way to do this in TypeScript is to use a class property to store the Region as follows (note that the alert is now commented ) :

class MarionetteApp extends Marionette.Application {
    navbarRegion: Marionette.Region;
    constructor() {
        super();
        this.on("initialize:after", this.initializeAfter);
        this.addRegions({ navbarRegion: "#navbarRegion" });
    }
    initializeAfter() {
        //alert("initializeAfter called");
    }
}

We will use this region as a content placeholder to render our Views a bit later on.

Creating a Marionette.View

In order to render something within the region, we will need to create a Marionette.ItemView.

In much the same way as we provided a <div> as the html template for a Marionette.Region, we provide a <script> block with a type of “text/template” to a Marionette.ItemView to use as an html template.  Modify your index.cshtml file to include the following:

        <script type="text/template" id="navBarItemViewTemplate">
            <p>NavBar View Template</p>
        </script>

To create a Marionette.ItemView in TypeScript, simply derive a class from Marionette.ItemView.  To do this, create a views directory under /tscode, and add a new TypeScript file named NavBarItemView.ts.

image

The code for NavBarItemView.ts is shown below.  Note that the reference paths at the top of this file will need to change slightly in order to correctly reference .d.ts files, as we are now two directories up from the base directory.

In the constructor we can see that the code is initializing the options parameter before it passes it to the base class.    To use the template that we created above, simply assign the template property of the options parameter to reference our <script> by id. :

/// <reference path="../../Scripts/typings/jquery/jquery.d.ts"/>
/// <reference path="../../Scripts/typings/underscore/underscore.d.ts"/>
/// <reference path="../../Scripts/typings/backbone/backbone.d.ts"/>
/// <reference path="../../Scripts/typings/marionette/marionette.d.ts"/> 

class NavBarItemView extends Marionette.ItemView {
    constructor(options?: any) {
        if (!options)
            options = {};
        options.template = "#navBarItemViewTemplate";
        super(options);
    }
}

Now modify your index.cshtml file to include the generated NavBarItemView.js file:

    <script language="javascript" type="text/javascript" src="../../tscode/MarionetteApp.js"></script>
    <script language="javascript" type="text/javascript" src="../../tscode/views/NavBarItemView.js"></script>
</head>

Lastly, modify the MarionetteApp to call show() on this view:

class MarionetteApp extends Marionette.Application {
    navbarRegion: Marionette.Region;
    constructor() {
        super();
        this.on("initialize:after", this.initializeAfter);
        this.addRegions({ navbarRegion: "#navbarRegion" });
    }
    initializeAfter() {
        //alert("initializeAfter called");
        this.navbarRegion.show(new NavBarItemView());
    }
}

If we run the application now ( hit F5 ) – we should see the “navBar region” text in the page replaced by the html we  specified in navBarItemViewTemplate :

image

Using bootstrap to create a clickable NavBar Button.

Our NavBarItemView is all well and good, but let’s do something useful with it. 

Most navigation bars are used to provide site-wide functionality – such as login / logout – so let’s update our NavBarItemView to show a boostrap button, and make it clickable.

To render our NavBarItemView as a bootstrap button, our template simply needs to have a css class assigned to it.  Modify the constructor of NavBarItemView to set the options.classname as follows:

class NavBarItemView extends Marionette.ItemView {
    constructor(options?: any) {
        if (!options)
            options = {};
        options.template = "#navBarItemViewTemplate";
        options.className = "btn btn-primary";
        super(options);
    }
}

Running the app now will assign the correct classnames to our template rendering it as a bootstrap button:

image

In order to make the button clickable, simply set the options.events property.  We will need to specify a function to call when the click event is fired.  This function can be called anything.  In the sample below, I’ve called it onClickEvent():

class NavItemBarView extends Marionette.ItemView {
    constructor(options?: any) {
        if (!options)
            options = {};
        options.template = "#navBarItemViewTemplate";
        options.className = "btn btn-primary";
        options.events = { "click": this.onClickEvent };
        super(options);
    }
    onClickEvent() {
        alert('NavBarItemView clicked');
    }
}

Run the app now, click on the navbar button, and verify that the event is fired correctly:

image

How simple was that ?

At this point it would be nice to render a couple of buttons in the navbar – but really this should be data-driven and not require too many changes to our ItemView.

Enter Backbone models and collections.

Let’s define a Backbone.Model to hold two properties for our buttons: Name and Id.  Then let’s create a collection of these models to drive rendering of multiple navbar buttons.

Using Backbone Models to drive NavBar buttons:

I’ve blogged previously about using strongly typed Backbone models with TypeScript. ( Can’t believe that was a year ago already ! ).   So if you would like a refresher then go an have a look.  Basically, we will be using ES5 syntax for model properties.  Go ahead and create a models directory under /tscode, and add a TypeScript file called NavBarButtonModel.ts.  Create a class that extends from Backbone.Model, called NavBarButtonModel.  Note that we also create a TypeScript interface definition for this model – which will help us when we start working with nested JSON and nested Backbone models and collections.

The constructor takes the INavBarButtonModel as input, and then sets each of the properties in the for loop.  This simple technique of using ES5 syntax and the constructor ensures that the model is synched with the underlying Backbone get and set functions, as well as giving us full type safety.

The source for NavBarButtonModel is as follows:

/// <reference path="../../Scripts/typings/jquery/jquery.d.ts"/>
/// <reference path="../../Scripts/typings/underscore/underscore.d.ts"/>
/// <reference path="../../Scripts/typings/backbone/backbone.d.ts"/>
/// <reference path="../../Scripts/typings/marionette/marionette.d.ts"/> 

interface INavBarButtonModel {
    Name?: string;
    Id?: number;
}

class NavBarButtonModel extends Backbone.Model implements INavBarButtonModel {
    get Name(): string { return this.get('Name'); }
    set Name(value: string) { this.set('Name', value); }

    get Id(): number { return this.get('Id'); }
    set Id(value: number) { this.set('Id', value); }

    constructor(input: INavBarButtonModel) {
        super();
        for (var key in input) {
            if (key) { this[key] = input[key]; }

        }
    }
}

Creating a Backbone.Collection to hold multiple Models.

Now that we have a Backbone.Model defined, lets define a Backbone.Collection to hold multiple buttons.  Create a NavBarButtonCollection.ts file in the models directory.  To define a Backbone.Collection, all we need to do is extend from Backbone.Collection, and set our model property to the name of the model class as follows.  Note that we have added a reference path at the top of the file to point to our model’s TypeScript file:

/// <reference path="../../Scripts/typings/jquery/jquery.d.ts"/>
/// <reference path="../../Scripts/typings/underscore/underscore.d.ts"/>
/// <reference path="../../Scripts/typings/backbone/backbone.d.ts"/>
/// <reference path="../../Scripts/typings/marionette/marionette.d.ts"/> 
/// <reference path="./NavBarButtonModel.ts" />

class NavBarButtonCollection extends Backbone.Collection {
    constructor(options?: any) {
        super(options);
        this.model = NavBarButtonModel;
    }
}

This collection will eventually be populated by JSON retrieved from a WebAPI service. But for now we can create a new collection as in the code below.  Note that this code is just a sample of how to create a collection – we will include it in the MarionetteApp.ts file a little later.:

        var navBarButtonCollection: NavBarButtonCollection = new NavBarButtonCollection(
            [
                { Name: "Home", Id: 1 },
                { Name: "About", Id: 2 },
                { Name: "Contact Us", Id: 3 }
            ]);

  But once we have a collection of NavBarButtonModels, we will need a new View to render the collection.

Creating a Marionette.CompositeView to render collections.

We now have most of the building blocks in place in order to render this collection on our page.  The final piece is a view that will take the NavBarButtonCollection as unput, and then instantiate a NavBarItemView for each model found in the collection.

Let’s create a new Marionette.CompositeView for this purpose.    As usual, we first need to create a <script> region in our Index.cshtml file – which will serve as the html template for our composite view.  Modify the Index.cshtml file to add a template with the id of navBarCollectionViewTemplate .  For the moment, we will simply define the template, but leave it blank as follows:

        <script type="text/template" id="navBarCollectionViewTemplate">
        </script>

Next, create a new TypeScript file under /tscode/views named NavBarCollectionView.ts.  This class will extend from Marionette.CompositeView.   As usual, specify the name of the html template in the options.template property as below:

Now we need to set the the itemView property to the class name of the view that is responsible for rendering an item – which in our case is NavBarItemView:

/// <reference path="../../Scripts/typings/jquery/jquery.d.ts"/>
/// <reference path="../../Scripts/typings/underscore/underscore.d.ts"/>
/// <reference path="../../Scripts/typings/backbone/backbone.d.ts"/>
/// <reference path="../../Scripts/typings/marionette/marionette.d.ts"/> 
/// <reference path="./NavBarItemView.ts"/> 

class NavBarCollectionView extends Marionette.CompositeView {
    constructor(options?: any) {
        if (!options)
            options = {};
        options.template = "#navBarCollectionViewTemplate";
        super(options);
        this.itemView = NavBarItemView;
    }
}

Next, we will need to include the new .js files in our Index.html <head> section:

    <script language="javascript" type="text/javascript" src="../../tscode/MarionetteApp.js"></script>

    <script language="javascript" type="text/javascript" src="../../tscode/views/NavBarItemView.js"></script>
    <script language="javascript" type="text/javascript" src="../../tscode/views/NavBarCollectionView.js"></script>
    
    <script language="javascript" type="text/javascript" src="../../tscode/models/NavBarButtonCollection.js"></script>
    <script language="javascript" type="text/javascript" src="../../tscode/models/NavBarButtonModel.js"></script>

Finally, we need to create an instance of the collection and pass it to the NavBarCollectionView.  Modify the MarionetteApp.ts file as shown below. 

Note that we create a NavBarButtonCollection by simply passing an array of objects – very similar to what raw JSON would look like.  Also, we create a NavBarCollectionView and pass it the collection in another JSON style object – by setting the collection property to the newly created NavBarButtonCollection:

class MarionetteApp extends Marionette.Application {
    navbarRegion: Marionette.Region;
    constructor() {
        super();
        this.on("initialize:after", this.initializeAfter);
        this.addRegions({ navbarRegion: "#navbarRegion" });
    }
    initializeAfter() {
        var navBarButtonCollection: NavBarButtonCollection = new NavBarButtonCollection(
            [
                { Name: "Home", Id: 1 },
                { Name: "About", Id: 2 },
                { Name: "Contact Us", Id: 3 }
            ]);

        this.navbarRegion.show(new NavBarCollectionView({ collection: navBarButtonCollection }));
    }
}

Firing up the app now should show us three buttons in our navbar – although it’s not quite what we envisaged.

image

Rendering Model Properties in templates.

What we really want here is to modify our ItemView template to display the Name value of the NavBarButtonModel instead of NavBarItem View Template.

Thankfully, it’s a piece of cake.

Modify the <script type="text/template" id="navBarItemViewTemplate"> tag in Index.cshtml as follows:

        <script type="text/template" id="navBarItemViewTemplate">
            <%= Name %>
        </script>

Running the app now will render the button names based on the model properties:

image

Finally, lets modify our click event in NavBarItemView to read the Id from the NavBarButtonModel:  You may notice that the call to get the Id property from the model is NOT using ES5 syntax.  As far as I understand, this is because Backbone is using the base Backbone.Model class internally, and therefore relies on the base get(‘attribute’) functions.

class NavBarItemView extends Marionette.ItemView {
    constructor(options?: any) {
        if (!options)
            options = {};
        options.template = "#navBarItemViewTemplate";
        options.className = "btn btn-primary";
        options.events = { "click": "onClickEvent" };
        super(options);
    }
    onClickEvent() {
        alert('NavBarItemView clicked with id :' + this.model.get('Id'));
    }
}

Clicking on any one of the buttons will now show a message with the model’s Id.

image

Triggering a Marionette event.

For the final exercise of Part 1, let’s use Marionette events to notify the MarionetteApp when someone clicks on a Navbar menu item.

Modify the onClickEvent() of the NavBarItemView to call Marionette’s trigger() function.  When triggering an event, we will need an event name (which can be anything), and we can also attach any data we need to the event.  In the code below, we are attaching the Model’s Id to the event.

class NavBarItemView extends Marionette.ItemView {
    constructor(options?: any) {
        if (!options)
            options = {};
        options.template = "#navBarItemViewTemplate";
        options.className = "btn btn-primary";
        options.events = { "click": "onClickEvent" };
        super(options);
    }
    onClickEvent() {
        this.trigger("navbar:clicked", this.model.get('Id'));
    }
}

Listening to a Marionette.Event

To handle this even, we will make some changes to the MarionetteApp.  Basically, just call the

on(‘eventname’,callback) method on the view, and provide a function callback (this.navBarButtonClicked).  Note too that the listening eventName is slightly different to the trigger eventName: itemview:navbar:clicked (handler) as opposed to just navbar:clicked ( trigger ).  This is because Marionette automatically attaches itemview: to any event that is fired by an ItemView.

Also note the signature of the callback method: we have two parameters – itemView and buttonId.  Again, Marionette always sends a handle to the originating ItemView as the first parameter to an event handler.  The second parameter therefore is our Model’s Id.

class MarionetteApp extends Marionette.Application {
    navbarRegion: Marionette.Region;
    constructor() {
        super();
        this.on("initialize:after", this.initializeAfter);
        this.addRegions({ navbarRegion: "#navbarRegion" });
    }
    initializeAfter() {
        var navBarButtonCollection: NavBarButtonCollection = new NavBarButtonCollection(
            [
                { Name: "Home", Id: 1 },
                { Name: "About", Id: 2 },
                { Name: "Contact Us", Id: 3 }
            ]);

        var navBarView = new NavBarCollectionView({ collection: navBarButtonCollection });

        navBarView.on("itemview:navbar:clicked", this.navBarButtonClicked);

        this.navbarRegion.show(navBarView);
    }

    navBarButtonClicked(itemView: Marionette.ItemView, buttonId: number) {
        alert('Marionette.App handled NavBarItemView clicked with id :' + buttonId);
    }

}

Running our App now – and clicking on a NavBarButton will then fire a Marionette event, which is then handled by the Marionette.App itself:

image

Well, that’s it for Part 1 of this article.

As mentioned, Part 2 of this article we will cover the following:

  • Creating an ASP.NET WebAPI Data Controller.
  • Unit testing the DataController in C#
  • Updating the NavBarButtonCollection to use our DataController.
  • Unit testing the NavBarButtonCollection using Jasmine.
  • Creating a Marionette.CompositeView to render data in a bootstrap table.

Have fun,

blorkfish.

Setting up TypeScript and AngularJs in Visual Studio 2013

Update : 6 Nov 2014

Update: Before you begin

In the 9 months or so since this blog post was published, WordPress has recorded over 10,000 page hits on this blog entry alone.  I wish it wasn’t so.  My experience with AngularJs (1.x) was frustrating to say the least.  Soon after posting this blog, I dropped AngularJs as a framework.  There were just too many things that should have been simple that I spent hours and hours trying to figure out – and still couldn’t get working.

As an example, when I tried to run an integration test to fetch json from my back-end database, I could not.  Every article I read said that I should mock out the http request and return mock data.  That is not the point of an integration test.  I need to ensure that the json returned from my service still works with my beautifully hand-crafted AngularJs application.  Angular’s unit testing framework would not allow me to do this.  So I gave up in favour of simpler, more object-oriented, more testable and eventually more explainable JavaScript framework.  But I did give it a good go.

A work colleague of mine sent me a link to a blog post today that just resonated with my own experiences.  Lars Eidnes has persisted with the AngularJs framework for a long time, and posted a blog entitled AngularJS: The Bad Parts.  It makes for a very interesting read.

In the end, choosing a framework is part personal choice, part experience, part guesswork.  My personal choice is not AngularJs.

Update: Angular 2.0

The recent announcement that the Microsoft and Angular teams have been working together on the Angular 2.0 framework is good news indeed.  The upcoming 1.5 version of the TypeScript compiler will include the first language structures to support Angular 2.0 syntax, and will include some elements of the AtScript language.  It will be a very interesting update,  with some very powerful new features.  Interesting times ahead, indeed.

Mastering TypeScript Book : available April 2015

Over the past couple of months I have been working very closely with the publishing team at PAKT Publishing on a new book called “Mastering TypeScript”.  It is scheduled for publication in April 2015.  The concepts and ideas of this blog post have all been updated and expanded within the book.  You can read all about it here : https://www.packtpub.com/web-development/mastering-typescript

B03967_MockupCover_Normal 

Original Post:

I have recently begun working through the AngularJs tutorials, and quickly found that they are geared towards development environments other than Visual Studio.  With the explosion of type definitions available via NuGet and DefinitelyTyped, I wanted to work through the process of getting up and running in AngularJs with a full Visual Studio 2013 development environment – complete with TypeScript debugging through F5.

As one of my passions is unit-testing, I was particularly interested in AngularJs’ methodology for writing and running Jasmine unit tests, as well as writing and running e2e tests. In addition, debugging unit tests and e2e tests was a must-have – thereby providing a complete Visual Studio development environment.

This blog therefore serves as a guide on how to setup TypeScript, AngularJs and Visual Studio 2013, including debugging Jasmine unit tests, debugging AngularJs e2e tests, and configuring a Continuous Integration build server ( TeamCity ).

Firstly, a few links:

AngularJs tutorial – this is the official AngularJs tutorial that I worked through in this blog.  Note that the source-code on git-hub currently covers step_00 through step_04.  Future blog entries will discuss step_05 and beyond.

The completed source-code for this project can be found on git-hub: blorkfish/TypeScriptAngularTutorial

I’ll follow the following steps :

  • Creating a TypeScript Project
  • Using NuGet to install AngularJs, boostrap, jasmine, and DefinitelyTyped definitions.
  • Writing TypeScript versions of the AngularJs controllers and unit tests.
  • Using node to setup karma
  • Debugging with Visual Studio 2013.
  • Debugging Unit tests with IE.
  • Debugging e2e tests with IE.
  • Notes on running tests on a CI build server.

Creating a TypeScript Project.

Let’s go ahead and create a TypeScript project in Visual Studio 2013.  Create a TypeScript Project.  For the purposes of this blog, I’ve called my project TypeScriptAngularTutorial.

image

Upgrade to .NET Framework 4.5

Note that to use the new Microsoft ASP.NET Web API 2.1, we’ll need to upgrade the project to use .NET 4.5.  Simply right-click on the project, select Properties, and modify the Target framework to .Net Framework 4.5:

image

Using NuGet to install dependencies.

Click on Tools | Library Package Manager | Manage NuGet packages for solution.  In the search box, simply type AngularJs:

I used the Angular Js package created by Fitzchak Yitzchaki, as it includes all of the angular js files in one hit:

image

Next, we need the angularjs.TypeScript.DefinitelyTyped package – as seen at the bottom of the list in the above screenshot.

Your project will now include a Scripts folder, with all of the relevant angular .js files, as well as a /Scripts/typings folder with all of the relevant .d.ts definition files for TypeScript:

image

Next, install NuGet packages bootstrap, jasmine, and jasmine.TypeScript.DefinitelyTyped.

image

image

Resolving issues with conflicting typings

At this stage, compiling the project will result in various errors relating to Duplicate Identifiers:

Duplicate identifier ‘describe’, ‘xdescribe’, ‘it’, ‘iit’, etc. etc.

This is due to multiple .d.ts files including definitions for the jasmine libraries.  To resolve this, edit the /Scripts/typings/angular-scenario.d.ts, and comment the definitions for describe etc. at the bottom of the file, and remove the /scripts/typings/jasmine/jasmine-1.3.d.ts file from the project.

image

Compiling the project now will produce 3 errors, all related to JasmineControler.cs.

image

This can be resolved by simply removing the JasmineController.cs file from the project.  It seems that the installation of Jasmine.js automatically adds a Jasmine MVC controller.  Since this is not an MVC project, the relevant MVC references have not been included.

Writing TypeScript versions of AngularJs Controllers and Unit Tests.

At this stage, we are ready to start writing AngularJs code.  Step_00 of the AngularJs Tutorial explains how to create app/index.html, and include the relevant angular.js files in order to see your first AngularJs application up and running.  The only difference between the Tutorial code and the Visual Studio version is the location of the AngularJs files.

Directory Structure

Using NuGet within Visual Studio will automatically create a /Scripts folder, and place JavaScript files in this folder.  NuGet will also place .css files in the /Content/ directory, and the TypeScript DefinitelyTyped definition files (.d.ts) will be downloaded in /Scripts/typings.

I have therefore kept the directory structure used in the tutorial the same as documented on the AngularJs site, and changed the references to /app/lib/ … to use the DifinitelyTyped structure of /Scripts/ …

Css files are split into two directories – those that are included with NuGetPackages are found in /Content, while those that you write yourself as part of the app I have put into the /app/css directory.

The script references for /app/default.html file for Step_00 are therefore as follows:

<head>
    <title>Tutorial app/index.html</title>
    <link rel="stylesheet" href="css/app.css"/>
    <link rel="stylesheet" href="../Content/bootstrap.css" />
    <script src="../Scripts/angular.js"></script>
</head>

Here is the resultant directory structure:

image

Debugging in Visual Studio

Note that setting /app/index.html as your project startup file, and debugging in Internet Explorer ( by hitting F5 ) may not currently have the desired effect.

If your page does not work correctly, i.e. shows Nothing here {{‘yet’ + ‘!}}, the problem is that IE is interpreting the page as an IE 7 standards page.

Include the <meta htp-equiv > tag line at the top of your /app/index.html page to force IE to use the latest version of the standards:

<!DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<html lang="en" ng-app="phonecatApp">
<head>

Writing the AngularJs Controller in TypeScript

In step_02 of the AngularJs Tutorial, you will begin writing an Angular Controller.  To do this in TypeScript, simply create a class, with a constructor that uses the $scope keyword.  Remember to include the angular.d.ts file for type definitions.

The full version of step_02 controller.ts is as follows:

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

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

class PhoneListCtrl  {
    constructor($scope) {
        $scope.phones = [
            { 'name': 'Nexus S', 'snippet': 'Fast just got faster' },
            { 'name': 'Motorola', 'snippet': 'Next generation tablet' },
            { 'name': 'Motorola Xoom', 'snippet': 'Next, next generation tablet' }
        ];
    }
};

If you would like to see the generated JavaScript version of this file, simply click on your project, and then “Show all files”.

At this stage, you should be able to put a breakpoint on the constructor above, hit F5, and debug directly into your TypeScript code.

Using node to setup Karma.

Karma setup is very straight-forward – simply install node and then install karma as directed in the tutorial.  NodeJs is a windows installer, and once installed, simply type

npm install -g karma

You will also need the karma-ng-scenario module.  If you would like to run tests in both Chrome ( the default ) and IE, simply install the karma-ie-launcher.  I use TeamCity for a CI build server, so also need karma-teamcity-reporter:

npm install -g karma-teamcity-reporter
npm install -g karma-ie-launcher
npm install -g karma-ng-scenario
npm install -g karma-junit-reporter

Note that on build servers, you will need to run the above commands while logged in as the account that executes the build.  Simply running the above as an Administrator will not install karma for all logged in users.

Running unit tests with Karma

With a little tweaking to the /test/config/karma.conf.js file to take into account the modified directory structure, running unit tests using karma is pretty simple – just navigate to the /test/scripts directory, and run test.bat.

Note that on build servers, simply append the —single-run parameter to the karma command line, which will run the tests once, and then quit the batch file.

Debugging TypeScript Unit Tests in Visual Studio.

Unfortunately, debugging TypeScript unit tests requires a running instance of Internet Explorer.  Similar to the /app/index.html file, we will need an .html file that we can set as the project startup file, and then simply hit F5 to start debugging unit tests.

In the source provided with this article, I have created two SpecRunner.html files – one for standard Jasmine unit tests, and the other for e2e AngularJs tests.  Instead of using karma as a test runner in this instance, we will simply use Jasmine.

/test/SpecRunner.html is as follows:

<!DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<html>
<head>
    <title>Partner Settings Test Suite</title>
    <!-- include your script files (notice that the jasmine source files have been added to the project) -->
    <script type="text/javascript" src="../Scripts/jasmine/jasmine.js"></script>
    <script type="text/javascript" src="../Scripts/jasmine/jasmine-html.js"></script>
    <script type="text/javascript" src="../Scripts/angular.js"></script>
    <script type="text/javascript" src="../Scripts/angular-mocks.js"></script>
    <script type="text/javascript" src="../app/ts/controllers.js"></script>
    <script type="text/javascript" src="unit/controllersSpec.js"></script>
    <link rel="stylesheet" href="../Content/jasmine/jasmine.css" />
</head>
<body>
    <!-- use Jasmine to run and display test results -->
    <script type="text/javascript">
        var jasmineEnv = jasmine.getEnv();
        jasmineEnv.addReporter(new jasmine.HtmlReporter());
        jasmineEnv.execute();
    </script>
</body>
</html>

Note that we have included jasmine.js and jasmine-html.js ( as well as the jasmine.css ) into the page, along with the required angular and controller javascript files.

Running the project with /test/SpecRunner.html as your startup page will allow you to set breakpoints in any of the above included javascript or typescript files.

image

Debugging TypeScript e2e tests with Visual Studio

Setting /test/e2e/SpecRunner.html as your project startup file will also enable debugging of e2e tests, when hitting F5 in Visual Studio.

image

If you would like to run the /test/script/test_e2e.bat file, just keep in mind that this requires a running web-server.  In Visual Studio, you need to hit F5 to start up IISExpress before running the batch file.  Otherwise, you will get an error as follows:

image

Note that in the /test/config/karma.e2e.js file there is a reference to proxies.  This sets the web-server site and port for the e2e tests to a running web-server instance.  In the properties of the project file, I have set the IIS Express port to be 53722, and this is the value of the proxies setting:

image

module.exports = function (config) {
    config.set({
        basePath: '../../',

        files: [
          'test/e2e/**/*.js'
        ],
        
        urlRoot: '/_karma_/',

        autoWatch: false,
        
        singleRun: true,
        
        proxies : {
            '/' : 'http://localhost:53722'
        },

Running tests on a CI build server.

To conclude, just a few notes on running tests on a CI build server.

In order to run unit tests on a CI build server ( such as TeamCity ), bear in mind the following:

  • Use the –-single-run parameter on the karma command line to run unit tests once only.
  • Depending on which build server you have, you may need either karma-junit-reporter, or karma-teamcity-reporter to report on unit test results correctly.
  • To launch tests in multiple browsers, make sure that you have installed the relevant launcher on the build server ( karma-chrome-launcher, karma-firefox-launcher, karma-ie-launcher).
  • Make sure that you log in as the account that runs the build to install karma and relevant reporters and launchers.
  • For e2e tests, a full version of the running web-site is required.
  • We use the Visual Studio packaging mechanism and msdeploy for automatic deployment on build servers.
  • Point your proxies setting in karma.e2e.conf.js to the web-site as above.
  • For web-servers that are behind a firewall, have a look at using cntlm local proxies.  This allows you to use your normal login on a server that does not have internet access.  All authentication is via a hash-key – so no username / passwords are in plain text.
    Have fun,
    – blorkfish.

TypeScript strongly typed Backbone Models

TypeScript and Backbone are a great fit in terms of writing simple, Object-Oriented code using JavaScript.  The simplicity of Backbone, coupled with the TypeScript generated closure syntax allow one to simply use the TypeScript extends keyword to derive from any of Backbone’s base classes – and start implementing functionality immediately.  This is a very natural way to write Object-Oriented JavaScript:

class ListItem extends Backbone.Model {

}

The problem with Backbone Models

Unfortunately, Backbone uses object attributes to store Model properties, and these need to be set in order for the Backbone model to work correctly.  The following code shows how to set Backbone Model properties:

class ListItem extends Backbone.Model {
    constructor() {
        super();
        this.set('Id', '2');
    }
}

The nature of the set and get functions of Backbone, however do not have any inherent type-safety.  These model properties are also not exposed as first-class object properties, and must always be accessed via the setter and getter functions.  A more natural way of expressing Backbone Models would be as follows:

class ListItem extends Backbone.Model {
    Id: number;
    Name: string;
    constructor() {
        super();
        this.Id = 2;
        this.Name = "ModelName";
    }
}

Using ES5 getter and setter syntax

The above effect can be achieve by using ES5 getter and setter syntax.  By defining a get and set function for each property, and then in turn calling the Backbone get and set functions, we can keep our Backbone Model in-synch with our TypeScript properties.

Note that you will need to switch your TypeScript project properties to compile to ES5 in order for the following code to work:

class ListItem extends Backbone.Model {
    get Id(): number {
        return this.get('Id');
    }
    set Id(value: number) {
        this.set('Id', value);
    }
    set Name(value: string) {
        this.set('Name', value);
    }
    get Name(): string {
        return this.get('Name');
    }

    constructor() {
        super();
        this.Id = 1;
        this.Name = "ModelName";
    }
}

Model Type-safety

We can further improve our model’s type-safety by using an interface – both for the implements keyword ( forcing our class to implement getters and setters for each interface property – and also for the object constructor.

Consider the following code:

interface IListItem {
    Id: number;
    Name: string;
    Description: string;
}

class ListItem extends Backbone.Model implements IListItem {
    get Id(): number        { return this.get('Id'); }
    set Id(value: number)   { this.set('Id', value); }
    set Name(value: string) { this.set('Name', value); }
    get Name(): string      { return this.get('Name'); }

    constructor(input: IListItem) {
        super();
        this.Id = input.Id;
        this.Name = input.Name;
    }
}

Note that we have defined an interface ( IListItem ), and forced the ListItem object to implement the interface.  We have also added the interface to the constructor, further enhancing our type-safety.

This ensures that changes to the interface will generate compile-time errors if the object does not have corresponding getter and setter functions, and also ensures that any object passed via the constructor will have all properties defined.

Simplifying the constructor

For a Backbone model with many properties, the constructor can further be simplified by looping through the properties of the input parameter as follows:

interface IListItem {
    Id: number;
    Name: string;
}

class ListItem extends Backbone.Model implements IListItem {
    get Id(): number { return this.get('Id'); }
    set Id(value: number) { this.set('Id', value); }
    set Name(value: string) { this.set('Name', value); }
    get Name(): string { return this.get('Name'); }

    constructor(input: IListItem) {
        super();
        for (var key in input) {
            if (key) {
                this[key] = input[key];
            }
        }
    }
}

A Jasmine Unit test

The above code will allow for both standard get and set Backbone syntax, as well as type-safe TypeScript syntax as shown in the following unit test:

describe("SampleApp : tests : models : ListItem_tests.ts ", () => {
    it("can construct a ListItem model", () => {
        var listItem = new ListItem(
            {
                Id: 1,
                Name: "TestName",
            });
        expect(listItem.get("Id")).toEqual(1);
        expect(listItem.get("Name")).toEqual("TestName");

        expect(listItem.Id).toEqual(1);

        listItem.Id = 5;
        expect(listItem.get("Id")).toEqual(5);

        listItem.set("Id", 20);
        expect(listItem.Id).toEqual(20);
    });

});

Note how a List Item is constructed with a standard JavaScript object definition.  Also, both listItem.Id or listItem.set(‘Id’, 20) syntax can be used to interact with a type-safe TypeScript Backbone model.

Have fun,

blorkfish.

Note : This blog post was as a result of a question posted on stackoverflow.com

Using ExtJs with TypeScript

Since the release of TypeScript there has been an explosion of JavaScript libraries that have had TypeScript definition files written for them.  A significant number can be found on borisjankov’s github repository  ( DefinatelyTyped ).

Unfortunately, there are currently no definition files for ExtJs in this repository.

Kudos to Mike Aubury (zz9pa) who has been able to use jsduck to reverse-engineer an ExtJs definition file from the ExtJs documentation, and load the project into his github repository ( extjsTypescript ).  For the purpose of this blog, I have had to modify Mike’s ExtJs.d.ts file generation slightly, just to mark each property and function as optional.  Read on to find out why.

This blog is the results of my initial findings attempting to use zz9pa’s ExtJs definitions with TypeScript.

ExtJs Class Structure

Lets have a look at a simple ExtJs Application :

Ext.application(
    {
        name: 'SampleApp',
        appFolder: '/code/sample',
        controllers: ['SampleController'],
        launch: () =>  {

            Ext.create('Ext.container.Viewport', {
                layout: 'fit',
                items: [{
                    xtype: 'panel',
                    title: 'Sample App',
                    html: 'This is a Sample Viewport'
                }]
            });

        }

    }
);

Note that the structure of ExtJs javascript is to instantiate objects with a configuration block as follows:

Ext.application(
    { 
        // Ext.application config block
    } 
);
Ext.create('Ext.container.Viewport', 
    {
        // viewport config block
    }
);

Compile time type-casting

The only way to utilize the powerful TypeScript benefits (i.e. type safety) is to manually type-cast these configuration blocks to the correct type by using compile time type casting as follows:

Ext.application(
    <Ext_app_Application>{ 
        // Ext.application config block
        // now has intellisense and type casting
    } 
);

With the above modification to the config block, we now have full intellisense, and type checking within our code.

A simple ExtJs Application with type-casting.

Let’s have a look at our sample application now utilizing the type-casting method as described above:

Ext.application(
    <Ext_app_Application> { // config block cast
        name: 'SampleApp',
        appFolder: '/app/sampleapp',
        controllers: ['SampleController'],
        launch: () =>  {

            Ext.create('Ext.container.Viewport', 
                <Ext_container_Viewport>{ // config block cast 
                layout: 'fit',
                items: [<Ext_panel_Panel>{
                    xtype: 'panel',
                    title: 'Sample App',
                    html: 'This is a Sample Viewport'
                }]
            });
        }
    }
);

ExtJs_Intellisense

Modifications to ExtJs.d.ts

In order to use the module definition for ExtJs ( extjsTypescript ) with this style of coding, we will need to modify the generated definition file to mark each property and function as optional :

Instead of this ( as an example)

interface Ext_AbstractPlugin extends Ext_Base {
   pluginId : String;
}

We need this:

interface Ext_AbstractPlugin extends Ext_Base {
   pluginId ? : String;
}

Note the ? optional flags for each of the properties and methods.

I have made some quick modifications to zz9pa’s code in order to make each property and function optional.  The Ext.d.ts file is included in the source download accompanying this blog.

The Ext namespace

The final modification that we need for the ExtJs definition file is for the Ext namespace itself.  This is where the majority of the work will be required to add further properties and function definitions for the Ext namespace.

Putting together this blog, and getting some samples up and running, I have defined only a tiny sub-set of the Ext namespace – mostly what I have needed to build a very simple application, and to start writing unit tests in Jasmine and Siesta.  So far, I have the following:

var Ext: IExt;
interface IExt {
    application(config: Ext_app_Application);
    Window: Ext_WindowManager;
    create(name: string, viewport: Ext_container_Viewport);
    getVersion();
    get (name: string): Ext_dom_AbstractElement;
    removeNode(name: Ext_dom_AbstractElement);
    DomHelper: Ext_DomHelper;
    getBody(): Ext_dom_AbstractElement;

    define(name: string, controller: Ext_app_Controller);
    define(name: string, controller: Ext_app_Application);

    ComponentManager: Ext_ComponentManager;
    require(name: string);
    onReady(call: Function);
}

Note that there are two define() functions, each with a different controller cast – as TypeScript will allow for function overloading.

ExtJs and TypeScript GOTCHA’s

Scope of this in config blocks and closures.

TypeScript uses the closure and module patterns extensively for it’s generated javascript.   One of the major advantages of these patterns is to correctly control scope, particularly for the ubiquitous this keyword.

In the following TypeScript code, init() will NEVER be called by ExtJs !

Note that init is a function returning this.control ( { … } ), and is using standard TypeScript syntax for specifying init as a function – the  () => { } syntax.

Ext.define('SampleApp.controller.FaultyController', <Ext_app_Controller>{
    extend: 'Ext.app.Controller',
    init: () => { 
        this.control({});
    },
});

The compiled code looks like this:

var _this = this;
Ext.define('SampleApp.controller.FaultyController', {
    extend: 'Ext.app.Controller',
    init: function () {
        _this.control({
        });
    }
});

Note the var _this = this; line at the top of the code, and how the init: function() will call _this.control – here we have an example of how TypeScript is using closures to ensure that we are scoping this correctly.

The solution : use anonymous functions

To resolve this issue, we will need to use standard javascript syntax for declaring anonymous functions inside our configuration block as follows:

Ext.define('SampleApp.controller.WorkingController', <Ext_app_Controller>{
    extend: 'Ext.app.Controller',
    init: function () {
        this.control({});
    }
});

Note the very subtle difference between init: () => {} syntax, and init: function() { } syntax.

The compiled version of the above code now works correctly with ExtJs:

Ext.define('SampleApp.controller.WorkingController', {
    extend: 'Ext.app.Controller',
    init: function () {
        this.control({
        });
    }
});

Unit Testing

The sample source code that is attached to this blog entry contains two test runners, one build for Jasmine, and another built for Siesta.

As my unit-testing tool of choice is Jasmine, I have put together more unit tests for Jasmine than for Siesta, but am also compiling some Siesta tests through TypeScript, just to show how to use Siesta.

One and only one Application

Each ExtJs solution can have one and only one Application defined, and jasmine tests need to be launched during global Application initialization – specifically during the launch function as follows:

Ext.onReady(() => {
    Ext.create('Ext.app.Application', <Ext_app_Application> {
        name: 'TestAppBootStrapper',
        appFolder: '../app/sampleapp',
launch: () => {

            jasmine.getEnv().addReporter(new jasmine.HtmlReporter());
            jasmine.getEnv().execute();
            return true;
        }
    });
});

Unfortunately, this presents some problems in test coverage, as initialization routines in either the main Application, or initialization for Controllers cannot be tested – or at least I have not found a way to do so.

Consider the following test:

    it('has called init on SampleController', () => {
        expect(SampleApp.getController('SampleController')).toBeDefined();

        // cannot spy on init function, as it is called before the tests start
        var spyOnInit = spyOn(SampleApp, 'init');
        expect(spyOnInit).toHaveBeenCalled(); // this will always fail

    });

This test will ALWAYS fail – as the init method of the SampleController ( the default controller for our Application ) is called BEFORE we have a chance to set a spy on the method.

In Conclusion : ExtJs objects vs TypeScript objects

Unfortunately, TypeScript and ExtJs do not seem to work too well together.  This incompatibility is mainly due to the differences in object creation between the two approaches.

Where ExtJs uses config blocks and anonymous methods for object creation, TypeScript uses the closure pattern to bring an easier way to build object-oriented javascript.  Unfortunately these two approaches seem to be at odds with each other.

Consider ExtJs’s method of object creation:

Ext.create(
    'Ext.container.Viewport', // object name
    <Ext_container_Viewport>{ // config block
        launch: function () { // anonymous method
        }
});

Each object is created with an object name ( global namespace ), followed by a configuration block and anonymous methods.  Having to statically cast each config block to the required type is a work-around to get Intellisense and type-checking into ExtJs code.

If the ExtJs libraries were written in a more TypeScript friendly manner, then we would be able to code like this:

// possible implementation of Ext.container.Viewport
class ExtContainerViewport {
    constructor(objectName: string) {
    }
    launch() {
    }
}

// extending an ExtContainerViewport is now more object-oriented.
class MyViewPort extends ExtContainerViewport {
    constructor() {
        super('MyViewPort');
    }
    launch() {
        super.launch();
    }
}

Have fun,

Blorkfish

Source Code Download

The full source code for this blog can be found here.  Note that in order to run the application, you will need the latest version of ExtJs which can be downloaded from here, as well as the latest version of siesta, which can be downloaded from here.

TypeScript: Organizing your code with AMD modules and require.js

TypeScript has two methods of generating JavaScript output files: CommonJS, and AMD.  CommonJS is the default, and amd modules can be generated by adding the –module AMD option to the compiler flags.

In this post, I’ll show how to create and use AMD modules, as well as configuring require.js by using require.config.

Update

This article has been updated to use TypeScript 0.9.  You can download / browse the source at github/blorkfish/typescript-amd-require-0.9

The older 0.8.1 source for this solution can be found here.

The older 0.8.0 source for this solution can be found here

Mastering TypeScript Book : available April 2015

Over the past couple of months, I have been working very closely with the publishing team at PAKT Publishing on a new book called “Mastering TypeScript”.  It is scheduled for publication in April 2015.  You can read all about it here:https://www.packtpub.com/web-development/mastering-typescript.

B03967_MockupCover_Normal

 

Creating a default project using CommonJS

Let’s start with a standard new TypeScript project – which by default creates an app.ts file, and a default.htm – and  add the following:

  • \app directory (for application files)
  • \app\classes (for our AMD classes)
  • \lib directory (for external libraries)
  • \modules (for our module definitions)
  • \app\AppMain.ts  ( note that you should remove any code that the compiler generates in this file)
  • \app\AppConfig.ts ( remove any code )
  • \app\classes\Greeter.ts ( remove any code )
  • download require.js and include it in the \lib directory. ( require.js can be found here release 2.1.8 )
  • download require.d.ts from DefinitelyTyped, and save it in the modules directory.

require_amd_1

\modules\Require.d.ts

As at the time of update, this is at version 2.1.1.

\app\classes\Greeter.ts as an AMD module

Cut the code defining the Greeter class from \app.ts into the \app\classes\Greeter.ts file:

Effectively, we are now starting to organise our project, with one .ts file for each class.

app\classes\Greeter.ts:
class Greeter {
    element: HTMLElement;
    span: HTMLElement;
    timerToken: number;

    constructor (element: HTMLElement) { 
        this.element = element;
        this.element.innerText += "The time is: ";
        this.span = document.createElement('span');
        this.element.appendChild(this.span);
        this.span.innerText = new Date().toUTCString();
    }

    start() {
        this.timerToken = setInterval(() => this.span.innerText = new Date().toUTCString(), 500);
    }

    stop() {
        clearTimeout(this.timerToken);
    }

}

Compiling the project now should show the error: Could not find symbo ‘Greeter’.

Let’s fix this first by using a CommonJS reference – add a reference path to app.ts:

app.ts
/// <reference path="app/classes/Greeter.ts" />

window.onload = () => {
    var el = document.getElementById('content');
    var greeter = new Greeter(el);
    greeter.start();
};

The project should now compile.

If you run the project now, (using Internet Explorer), the Greeter.js file will be unreferenced:

0x800a1391 – JavaScript runtime error: ‘Greeter’ is undefined

The simple solution is to include this new Greeter.js file in default.htm:

default.htm
<head>
    <meta charset="utf-8" />
    <title>TypeScript HTML App</title>
    <link rel="stylesheet" href="app.css" type="text/css" />
    <script type="text/javascript" src="app/classes/Greeter.js"></script>
    <script src="app.js"></script>
</head>

Running the project now will succeed:

typescript_amd_1

Converting Greeter.ts to an AMD module

TypeScript 0.9 and upwards will default to compile all source files as AMD compliant.  This is slightly different to 0.8 versions, where by default projects were compiled to commonJS.  For reference purposes, the following section shows how to use AMD in 0.8 versions.  If using TypeScript 0.9, please continue to the next section, Export Greeter.

Specifying AMD compilation for 0.8 and 0.8.1 versions of TypeScript:

To compile project files to AMD modules, unload your project file, edit it, and add the –module AMD option to the command line options:

0.8.1

:  Here is the 0.8.1 version of the project file:

Note that you will need to remove the –sourcemap option for Debug configuration, as sourcemap and AMD do not work well together.

  <PropertyGroup Condition="'$(Configuration)' == 'Debug'">
    <!--remove the --sourcemap option below-->
    <TypeScriptSourceMap></TypeScriptSourceMap>
  </PropertyGroup>
  <Target Name="BeforeBuild">
    <Message Text="Compiling TypeScript files" />
    <Message Text="Executing tsc$(TypeScriptSourceMap) @(TypeScriptCompile ->'&quot;%(fullpath)&quot;', ' ')" />
    <Exec Command="tsc$(TypeScriptSourceMap) --module AMD @(TypeScriptCompile ->'&quot;%(fullpath)&quot;', ' ')" />
  </Target>

Older version 0.8.0 compiler version:

  <Target Name="BeforeBuild">
    <Exec Command="&quot;$(PROGRAMFILES)\Microsoft SDKs\TypeScript.8.0.0\tsc&quot; --module AMD @(TypeScriptCompile ->'&quot;%(fullpath)&quot;', ' ')" />
  </Target>

Export Greeter

Before we change app\classes\Greeter.ts to an AMD module, have a look at the generated javascript source :

var Greeter = (function () {
    function Greeter(element) {
        this.element = element;
        this.element.innerHTML += "The time is: ";
        this.span = document.createElement('span');
        this.element.appendChild(this.span);
        this.span.innerText = new Date().toUTCString();
    }
    Greeter.prototype.start = function () {
        var _this = this;
        this.timerToken = setInterval(function () {
            return _this.span.innerHTML = new Date().toUTCString();
        }, 500);
    };

    Greeter.prototype.stop = function () {
        clearTimeout(this.timerToken);
    };
    return Greeter;
})();
//@ sourceMappingURL=Greeter.js.map

Now modify the Greeter class definition, and add the export keyword:

app/classes/Greeter.ts
export class Greeter {

AMD compliant javascript source.

After compiling, Note the changes to the javascript source – the entire code block has been wrapped in a define( […] ) block, and there is an extra exports.Greeter = Greeter; line at the bottom of the file:

define(["require", "exports"], function(require, exports) {
    var Greeter = (function () {
        function Greeter(element) {
            this.element = element;
            this.element.innerHTML += "The time is: ";
            this.span = document.createElement('span');
            this.element.appendChild(this.span);
            this.span.innerText = new Date().toUTCString();
        }
        Greeter.prototype.start = function () {
            var _this = this;
            this.timerToken = setInterval(function () {
                return _this.span.innerHTML = new Date().toUTCString();
            }, 500);
        };

        Greeter.prototype.stop = function () {
            clearTimeout(this.timerToken);
        };
        return Greeter;
    })();
    exports.Greeter = Greeter;
});
//@ sourceMappingURL=Greeter.js.map

Compiling at this stage will generate errors : Could not find symbol ‘Greeter’.

We now need to modify the app.ts file to import the the module.  Remove the ///reference path line, and add an import statement as below:

Now use the name of the import ( gt ) to reference gt.Greeter :

app.ts
import gt = module("app/classes/Greeter");

window.onload = () => {
    var el = document.getElementById('content');
    var greeter = new gt.Greeter(el);
    greeter.start();
};

Running the app at this stage now will produce the following error:

Unhandled exception at line 1, column 1 in http://localhost:8524/app.js

0x800a1391 – JavaScript runtime error: ‘define’ is undefined

This error is because define is part of the require.js library, as seen at the end of the require.d.ts file :

// Ambient declarations for 'require' and 'define'
declare var require: Require;
declare var requirejs: Require;
declare var req: Require;
declare var define: RequireDefine;

Configuring require.js

In order to use AMD modules, we need to tell our page to include require.js.  Looking at the require.js documentation, the way to do this is to include the following in your html page

default.htm :

<script data-main="app/AppConfig" type="text/javascript" src="lib/require.js"></script>

Note that the require.js syntax is to use the data-main property to specify a JavaScript file to load as the initial starting point for the application – in this case : app/AppConfig.js.

Remove the reference to Greeter.js, and app.js, so that your default.htm file looks like this:

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>TypeScript HTML App</title>
    <link rel="stylesheet" href="app.css" type="text/css" />
    <script data-main="app/AppConfig" type="text/javascript" src="lib/require.js"></script>
</head>
<body>
    <h1>TypeScript HTML App</h1>

    <div id="content"></div>
</body>
</html>

AppConfig.ts

Create an app/AppConfig.ts TypeScript file, as follows:

app/AppConfig.ts
/// <reference path="../modules/require.d.ts" />

import gt = module("classes/Greeter");

require([], () => {
    // code from window.onload
    var el = document.getElementById('content');
    var greeter = new gt.Greeter(el);
    greeter.start();
});

Note that we have moved the application startup code (the window.onload function) into the body of the require function.

The app should now run using AMD loading.

Adding further modules

Should your application require further AMD modules, simply include them in the /lib directory, and specify them in the first array  as follows:

app/AppConfig.ts
require(['../lib/jquery-1.7.2','../lib/underscore', '../lib/backbone', '../lib/console'], () => {
    // code from window.onload
    var el = document.getElementById('content');
    var greeter = new gt.Greeter(el);
    greeter.start();
});

Note that the paths for require are relevant to the location of the AppConfig.ts file (which is in the app directory).

Using require.config

require.js has a number of configuration options that make it so powerful.  Among these is the ability to define dependencies between modules.

Unfortunately, including a require.config in our app/AppConfig.ts file as shown below will result in a run-time error:

0x800a01b6 – JavaScript runtime error: Object doesn’t support property or method ‘config’

app/AppConfig.ts
/// <reference path="../modules/require.d.ts" />

// the config below will cause a run-time error
require.config({
    baseUrl: '../'
});

import gt = module("classes/Greeter");

require(['../lib/jquery-1.7.2','../lib/underscore', '../lib/backbone', '../lib/console'], () => {
    // code from window.onload
    var el = document.getElementById('content');
    var greeter = new gt.Greeter(el);
    greeter.start();
});

This run-time error is caused because the TypeScript compiler ( with –module AMD ) compile option wraps the entire file in a require statement.  Have a look at the generated code:

app/AppConfig.js (generated)
define(["require", "exports", "classes/Greeter"], function (require, exports, __gt__) {
    // this require.config below should NOT be inside the define function
    require.config({
        baseUrl: '../'
    });
    var gt = __gt__;

    require([
        '../lib/jquery-1.7.2', 
        '../lib/underscore', 
        '../lib/backbone', 
        '../lib/console'
    ], function () {
        var el = document.getElementById('content');
        var greeter = new gt.Greeter(el);
        greeter.start();
    });
})

Using require.config with AMD modules solution:

The solution here is to separate our require config file from our application main file, and remove any import module statements from the configuration file.  Remember how the generated javascript changed when we added the import statement to app/classes/Greeter.ts ? So make sure that the file with require.config does not have any import statements :

AppMain.ts

Create an AppMain.ts file within the app folder as follows:

app/AppMain.ts
import gt = module("classes/Greeter");

export class AppMain {
    public run() {
        var el = document.getElementById('content');
        var greeter = new gt.Greeter(el);
        greeter.start();

    }
}

Modify AppConfig.ts to use named require parameters

app/AppConfig.ts
/// <reference path="../modules/require.d.ts" />
/// <reference path="AppMain.ts" />
require.config({
    //baseUrl: '../' // commented for now
});

require(['AppMain', 
    '../lib/jquery-1.7.2','../lib/underscore', '../lib/backbone', '../lib/console' ], 
    (main) => {
    // code from window.onload
    var appMain = new main.AppMain();
    appMain.run();
});

Note that we have specified to require.js that it must load a file named ‘AppMain’ ( our AppMain.ts compiled file), and that when the require function runs, AppMain’s classes will be referenced by the named parameter main. If we were to name all of the parameters in the require array, our code would look something like this:

app/AppConfig.ts
require(['AppMain', 
    '../lib/jquery-1.7.2','../lib/underscore', '../lib/backbone', '../lib/console' ], 
    (main, $, _, console) => {
    var appMain = new main.AppMain();
    appMain.run();
});

Using named require parameters and shims

Fortunately, require.js allows us to configure named parameters via the paths config variable, and then define a shim property for each named path, that includes the export symbol, and any dependencies, as follows:

app/AppConfig.ts
require.config({
    baseUrl: '../',
    paths: {
        'jquery': 'lib/jquery-1.7.2',
        'underscore': 'lib/underscore',
        'backbone': 'lib/backbone',
        'console': 'lib/console'
    }, 
    shim: {
        jquery: {
            exports: '$'
        },
        underscore: {
            exports: '_'
        },
        backbone: {
            deps: ["underscore", "jquery"],
            exports: "Backbone"
        },
        console: {
            exports: "console"
        }
    }
});

require([
     'jquery'
    , 'underscore'
    , 'backbone'
    , 'console'
    ], 
    ($, _, Backbone, console) => {
    $(() => {

        // code goes here

    });
});

Require.config tips

Note that for jquery plugins – all jquery extension methods must export to $ as well – this is accomplished by specifying $ as the export for plugins, and jquery as a dependency.  Note too that in the require function definition, TypeScript will not allow multiple parameters with the same name, so to use jquery.flip.js for example, use the following require.config:

require.config({
    paths: {
        'jquery': 'lib/jquery-1.7.2',
        'jqueryflip': 'lib/jquery-flip'
    },
    shim: {
        jquery: {
            exports: '$'
        },
        jqueryflip: {
            deps: ['jquery'],
            exports: '$'
        }
    }
});

require(['jquery', 'jqueryflip', 'AppMain'], ($, jqueryflip, main) => {
    var appMain = new main.AppMain();
    appMain.run();
});

Have fun,

– Blorkfish.

TypeScript: Implementing a Simple IOC Container for Service Location

Introduction

Inversion of Control is an object-oriented design pattern that encourages de-coupling of objects, by enforcing a layer of abstraction between object interfaces.

The purpose of this post is to explain how to implement a very simple IOC container using TypeScript, focussing on a Service Locator.  This IOC container can be used both for service location of TypeScript generated classes, and external JavaScript libraries.

Update

I have just setup a github repository for TypScriptTinyIoC : https://github.com/blorkfish/typescript-tiny-ioc

End Goal

Our end goal is to be able to use a very simple IOC for service location as follows:

// registration
var typeScriptTinyIoC = new TypeScriptTinyIOC();
TypeScriptTinyIOC.register(new TestImplementsIDrawable(), new IIDrawable());

// service location
var implementsIDrawable = TypeScriptTinyIOC.resolve(new IIDrawable());
expect(implementsIDrawable.draw()).toEqual("drawn");

Reflection (of sorts)

Unfortunately, JavaScript does not support reflection – which is a pre-requisite for IOC containers.  It does, however allow for querying an object for a specific method.  In their book, “Pro JavaScript Design Patterns”, Ross Harmes and Dustin Diaz explain how:

Consider the following code:

class Greeter {
    start() {
    }
}

class FunctionChecker {
    static implementsFunction(objectToCheck: any, functionName: string): bool {
        return objectToCheck[functionName] != undefined;
    };
}

window.onload = () => {
    var greeter = new Greeter();
    var el = document.getElementById('content');
    el.innerHTML = 'Does greeter implement start() ' +
        FunctionChecker.implementsFunction(greeter, 'start');
};

This very simple function checking algorithm will test whether the instance of greeter implements the function start.

Taking this principle one step further, lets define a TypeScript interface with a class name, and a simple array of method names,

interface IInterfaceChecker {
    className: string;
    methodNames: string[];
}

Then we can define a class that implements this InterfaceChecking interface.

export class IITodoService implements IInterfaceChecker {
    className: string = 'IITodoService';
    methodNames: string[] = ['loadMTodoArray', 'storeMTodoArray'];
};

Static Reflection

I guess that you can think of this mechanism as “static reflection”, or “manual reflection”, because we still need to define the list of method names manually.  There are benefits to this approach, though.

Interface Checking Benefits.

While this very simple mechanism may seem trivial, it’s beauty is in it’s simplicity.  It is easy to implement, and promotes reusability – because classes will have documented sets of methods, and can easily be swapped out for different classes that implement the same functionality.

It also provides us a mechanism of determining (at runtime) whether a class implements the desired functionality – and can also be invaluable when your classes depend on external libraries.  Whenever a new version is available, the library can be checked against your list of required functionality.

TypeScript Interfaces

While TypeScript provides the mechanism for strict compile-time checking of interfaces, at run-time we are still dealing with plain-old JavaScript, so the interface definitions are compiled away.  For this reason, we will define a real TypeScript interface, as well as an InterfaceChecker interface definition for use in our InterfaceChecker.  This can be easily accomplished through a simple naming standard:

A simple naming standard I-name and II-name

For standard TypeScript Interfaces, pre-fix the interface with the letter I (as per C# standards) – and for InterfaceChecker Interface definitions, prefix the class name with a double I :

This is the standard TypeScript interface for a TodoService:

interface ITodoService {
    loadMTodoArray() : any [];
    storeMTodoArray(inArray: any[]) : void;
};

and the InterfaceChecker class:

export class IITodoService implements IInterfaceChecker {
    className: string = 'IITodoService';
    methodNames: string[] = ['loadMTodoArray', 'storeMTodoArray'];
};

Then a class that implements the ITodoService :

export class ToDoService implements ITodoService {
    loadMTodoArray(): any [] {
        // load and return an array of objects
        return [{ id: 5},{ id: 6},{ id: 7}];
    };
    storeMTodoArray(inArray: any[]): void {
        // persist here
    };
}

Interface Checking

Our run-time check to ensure that the TodoService class implements ITodoService is then as follows:

var service = new TodoService();
InterfaceChecker.ensureImplements(service , new IITodoService()); 
// above will throw if not implemented

InterfaceChecker

The full code for our interface checker is as follows:

class InterfaceChecker {
    name: string;
    methods: string[];

    constructor (object: IInterfaceChecker) {
        this.name = object.className;
        this.methods = [];
        var i, len: number;
        for (i = 0, len = object.methodNames.length; i < len ; i++) {
            this.methods.push(object.methodNames[i]);
        };
    }

    static ensureImplements(object: any, targetInterface: InterfaceChecker) {
        var i, len: number;
        for (i = 0, len = targetInterface.methods.length; i < len; i++) {
            var method: string = targetInterface.methods[i];
            if (!object[method] || typeof object[method] !== 'function') {
                throw new Error("Function InterfaceChecker.ensureImplements: ' + '
                    object does not implement the " + targetInterface.name +
                    " interface. Method " + method + " was not found");
            }
        }
    };
    static implementsInterface(object: any, targetInterface: InterfaceChecker) {
        var i, len: number;
        for (i = 0, len = targetInterface.methods.length; i < len; i++) {
            var method: string = targetInterface.methods[i];
            if (!object[method] || typeof object[method] !== 'function') {
                return false;
            }
        }
        return true;
    };
}

Once we have the mechanics of our InterfaceChecker in place, it is very simple to implement an IOC container for service Location:

TypeScriptTinyIOC

class TypeScriptTinyIOC {

    static registeredClasses: any[] = [];

    static register(targetObject: any, interfaceType: IInterfaceChecker) {
        var interfaceToImplement = new InterfaceChecker(interfaceType);

        InterfaceChecker.ensureImplements(targetObject, interfaceToImplement); 
        // will throw if not implemented
        if (InterfaceChecker.implementsInterface(targetObject, 
            interfaceToImplement)) 
        {
            this.registeredClasses[interfaceType.className] = targetObject;
        }
    }

    static resolve(interfaceType: IInterfaceChecker): any {
        var resolvedInterface = this.registeredClasses[interfaceType.className];
        if (resolvedInterface == undefined)
            throw new Error("Cannot find registered class that implements " 
                + " interface: " + interfaceType.className);
        return resolvedInterface;
    }

};

TypeScriptTinyIOC usage:

The very simple IOC container can then be used as follows:

interface IDrawable {
    centerOnPoint();
    zoom();
    draw(): string;
}

class IIDrawable implements IInterfaceChecker {
    className: string = 'IIDrawable';
    methodNames: string[] = ['centerOnPoint', 'zoom', 'draw'];
}

class TestImplementsIDrawable implements IDrawable {
    centerOnPoint() {
    };
    zoom() {
    };
    draw() : string {
        return 'drawn';
    };
}

// registration
var typeScriptTinyIoC = new TypeScriptTinyIOC();
TypeScriptTinyIOC.register(new TestImplementsIDrawable(), new IIDrawable());

// service location
var implementsIDrawable = TypeScriptTinyIOC.resolve(new IIDrawable());
expect(implementsIDrawable.draw()).toEqual("drawn");

Have fun,

– Blorkfish.

In my next blog post, I will be tackling TypeScript AMD modules – understanding how to create and use them, how they help with code organisation, and how to mix standard TypeScript classes with AMD modules.

TypeScript and Backbone / Sinon Gotchas

Over the past few days I have been working through Jim Newbery’s excellent tutorial on testing Backbone applications with Jasmine and Sinon.

I just wanted to share a few gotcha’s that I experienced where TypeScript differs slightly from standard JavaScript.

1. Backbone default properties

Consider the following code:

var TodoListView = Backbone.View.extend({
    tagname: 'ul',
    className: 'todos'
});

The TypeScript equivalent would be the following:

class TodoListView extends Backbone.View {
    tagname: string = 'ul';
    className: string = 'todos';
}

Unfortunately, once the class is created, the tagname: and className: properties will be undefined.

Solution:

Set any default properties in the constructor:

class TodoListView extends Backbone.View {
    tagname: string;
    className: string;
    constructor (options?: any) {
        this.tagname = 'ul';
        this.className = 'todos';
        super(options);
    };
}

2. Backbone.Model setting attributes from default:

Consider the following JavaScript:

var Todo = Backbone.Model.extend({
    defaults: {
        'priority': 3
    }
});

In TypeScript, this should be written as:

class Todo extends Backbone.Model {
    defaults: {
        id: 0,
        priority: 0
    };
}

However, this will not compile, and generates the following error:

Expected type name

Solution :

defaults: any = {
                id: 0,
                priority: 0
        };

Note :

The official Microsoft release includes a solution that looks very convoluted :

class Todo extends Backbone.Model {
    initialize() {
        if (!this.get('id')) {
            this.set({ 'id': this.defaults().id });
        }
        if (!this.get('priority')) {
            this.set({ 'priority': this.defaults().priority });
        }

    };
    defaults() {
            return {
                id: 0,
                priority: 0,
            }
        };
}

3. Returning JSON responses with sinon.FakeServer.

Consider the following standard JavaScript code:

this.server.respondWith("GET", "/collection",
    [200, {"Content-Type": "application/json"},'{"id":123,"title":"Hollywood - Part 2"}']);

Unfortunately, this will generate an error message as follows.

Incompatible types in array literal expression

As far as I understand, this is due to mixing types in an array – which by TypeScript standards is not allowed.

Note that 200 is a number, {“Content-Type”: “application/json”} is an Object, and ‘{“id”… is a string.

Solution:

The only way that I have found around this is to drop the JSON return code and content type, and return just the string:

this.server.respondWith("GET", "/collection", JSON.stringify(this.fixture));

Have fun.

Including TypeScript comments in generated JavaScript

Just a quick one for those needing typescript comments to be included in generated JavaScript files.

The TypeScript compiler has the –c option to included comments, but this option is not available when working with Visual Studio.

The simple solution is to modify the .csproj project file and included –c in the call to the TypeScript compiler.

  • Right-click on your project file in Visual Studio, and click Unload Project.
  • Right-click again on the project file, and select Edit <your project name>.csproj

This will bring up the xml project file in edit mode.

Scroll down to the bottom of the file, and locate the following snippet:

  <Target Name="BeforeBuild">
    <Exec Command="&amp;quot;$(PROGRAMFILES)\Microsoft SDKs\TypeScript\0.8.0.0\tsc&amp;quot; @(TypeScriptCompile ->'&quot;%(fullpath)&quot;', ' ')" />
  </Target>

Now add a –c after the tsc&amp;quot; and before the @(TypeScriptCompile as follows:

From:
\TypeScript.8.0.0\tsc&quot; @(TypeScriptCompile ->

To:

\TypeScript.8.0.0\tsc&quot; -c @(TypeScriptCompile ->

Save the project file, and re-load it.

TypeScript will now include all comments within a .ts file into the generated .js file.

Have fun,

– Blorkfish

TypeScript unit testing with Visual Studio 2012, jasmine, backbone, sinon, require and testem on Windows 7

This blog is a starting point for those who are just getting into TypeScript development (like all of us I guess), and need a workable unit testing framework.

While my initial preference was to try and integrate TypeScript with Chutzpah, I ran across a few issues where changes to TypeScript files were not being picked up by the Test Discoverer.  Unit testing therefore with Chutzpah will need to wait until official support has been added.

The full solution used for this walkthrough can be downloaded from skydrive (TypeScriptSampleApp.zip) here.

UPDATE 10th October 2012:

Many thanks to Jim Newbery, over at tinnedfruit for this excellent tutorial, which has been the reference that I have been working from.  I have just updated the download to include tests from Part 1, Part 2, and Part 3.

Software Pre-requisites

This walkthrough uses the following software:

  • TypeScript : Download the installation media (for Windows) here.
  • Node.js
    • Node.js is a platform built on Chrome’s JavaScript runtime for building fast, scalable network applications.
    • It is a pre-requisite for testem, and can be downloaded here.
  • Jasmine.js :
    • Jasmine is a behaviour-driven development framework for testing JavaScript code.
    • The github wiki site is here.
  • Underscore.js:
    • Underscore.js is a pre-requisite for Backbone.js, and can be found here.
  • Backbonejs:
    • Backbone.js is a popular JavaScript library that gives structure to web applications.
    • The home page is here.
  • Sinon.js:
    • Sinon.js is a mocking and spying framework for JavaScript testing.
    • The home page is here.
  • Require.js:
    • Require.js is a JavaScript file and module loader.
    • It can be downloaded from here.
  • Testem:
    • Testem is a test runner from Toby Ho which provides an auto-re-run-on-save for test driven development.
    • Toby’s blog post on testem, including links is here.

TypeScript Setup

The TypeScript installation process is straight-forward, simply download the installation .msi from and run it.

Create a new TypeScript Project

From within Visual Studio, create a new project using the HTML Application with TypeScript template.

TypeScript_newProject

Project Structure

Testem will run unit-tests found in a particular directory, and by default it is the current directory that testem is launched from.

Unfortunately, this will cause errors when JavaScript library files and includes are in different directories.  For this reason, I have structured my project as follows:

\  (root directory)

  • This is the base directory of the project.
  • The following files should be present here:
  • testem.yml
    • this is the testem configuration file, and points to the various directories as below.
  • SpecRunner.html
    • This is the standard Jasmine SpecRunner.html file from the source, and has been modified as per the various directories below.
    • Note that I have included this file for manual debugging purposes.

\lib

  • the lib directory will contain all required JavaScript library downloads ( except for jasmine ).
  • I have had problems with the Testem runner if the jasmine.js files are in this directory.
  • the following files should be present in this directory:
    • backbone.js
    • require.js
    • sinon-1.4.2.js
    • underscore.js

\lib\jasmine

  • this folder will house the jasmine.js downloads – and are used only for manual de-bugging purposes.
  • As mentioned before, having these files in the parent \lib directory will cause problems with testem.

\test

  • this folder contains TypeScript testing files

\tests\sub_folder

  • This folder contains more TypeScript testing files – it is here simply to test that Testem can traverse sub-folders when looking for tests.

\modules

  • This folder contains the TypeScript .d.ts modules that are referenced in the tests.
  • As your project grows, you will be updating the module files to provide better type safety for external JavaScript libraries
  • The following files should be present in this directory:
    • Backbone.d.ts
    • Jasmine.d.ts
    • require.d.ts
    • sinon.d.ts

A screenshot of the Directory structure from Visual Studio is as follows:

TypeScript_VisualStudio_snapshot

Running Testem

Once testem is installed, simply fire up a command prompt, and change to the root directory of your project.

Before we run testem, lets have a look a the testem.yml file a the base of the project directory:

framework: jasmine
src_files:
- lib/require.js
- tests/**/*.js
  • Note that we are using jasmine as the testing framework.
  • src_files points to the directories in which to find tests, as well as javascript files that are required for each run.
    • by using lib/require.js, we can inject further required javascript files into our tests as dependencies.
    • tests/**/*.js specifies that all javascript files in the tests directory, and any sub-directories will be scanned for tests.
Fire up testem by running testem on the command line.

You should see testem start, and then show “Waiting for runners…”

TypeScript_testem_1

Now fire up a browser, and type in the url shown in the top-left-hand corner of testem.  In this case, it’s http://localhost:7357

Congratulations, your unit tests should now run.

TypeScript_testem_2

And the testem runner:

TypeScript_testem_3

Anatomy of a test

Lets have a quick look at the code of a sample test.

Firstly, we need to include references to our modules in order for TypeScript to allow us to compile our tests:

/// <reference path="../modules/Jasmine.d.ts" />
/// <reference path="../modules/require.d.ts" />
/// <reference path="../modules/Backbone.d.ts" />

TypeScript Modules

As your project matures, and the list of functions you are using extends, you will need to update these module files with function signatures that match any function or property that you are accessing from and external library.

If we look at Jasmine.d.ts, we will notice that it has function signatures that cover the describe, it, expect, beforeEach and afterEach functions:

// module for Jasmine

declare module describe {
    export function(testDescription: string, f: Function) : any ;
}

declare module it {
    export function(testDescription: string, f: Function) : any ;
}

declare module expect {
    export function (actual: any): any;
}

declare module beforeEach {
    export function (f: Function): any;
}

declare module afterEach {
    export function (f: Function): any;
}

The test itself:

Lets now have a look at the code for a standard jasmine unit test:

describe("Jasmine_ModelTests:", function () {
    it("should pass a simple test", function () {
        expect("test").toEqual("test");
    });
});

Pretty self-explanatory.

Using require.js in tests that target further frameworks:

The following test is using backbone.js as a framework, and therefore needs to include underscore.js and backbone.js as test dependencies:

require(["lib/underscore.js","lib/backbone.js"], function () {
    describe("Jasmine_ModelTests_with_require:", function () {
        it("should pass a simple test with backbone", function () {
            var model = new Backbone.Model({
                name: "myName",
                title: "myTitle"
            });

            expect(model.get("name")).toEqual("myName");
            expect(model.get("title")).toEqual("myTitle");
        });
    });
});

Note here the first line of the test is a call to require to load both underscore.js and backbone.js before the test begins.

TypeScript require function call structure

One important thing to note here is the structure of the function call.
According to require.js documentation, the function call should be as follows (outlined in red):

require(["lib/underscore.js", "lib/backbone.js"], function (underscore, backbone) {
    // underscore and backbone are now fully fledged namespaces
});

Note that this convention will allow code within the require block to use underscore as a namespace, and backbone as a name space as follows:

var model = new backbone.Model({
                name: "myName",
                title: "myTitle"
            });

Unfortunately, this will break TypeScript’s auto-completion and Intellisense, as it cannot find a reference to backbone in any of the module definitions.

For this reason, it is better for TypeScript to use the function call without specifying namespaces, as follows:

require(["lib/underscore.js","lib/backbone.js"], function () {

});

Finally

The purpose of this blog has just been to get an automated unit testing framework running with TypeScript.
My understanding of the TypeScript language annotations, as well their use – will grow in time, so I would welcome any comments or suggestions that you have in this regard.

Have fun,
– Blorkfish.