A few days ago, I gave a talk on building Single Page Apps on the Microsoft Stack. In that talk, I recommended that people use Knockout, Sammy, and RequireJS to build their presentation layer and use the ASP.NET Web API to expose data from their server.
After I gave the talk, several people contacted me and suggested that I investigate a new open-source JavaScript library named Durandal. Durandal stitches together Knockout, Sammy, and RequireJS to make it easier to use these technologies together.
In this blog entry, I want to provide a brief walkthrough of using Durandal to create a simple Single Page App. I am going to demonstrate how you can create a simple Movies App which contains (virtual) pages for viewing a list of movies, adding new movies, and viewing movie details. The goal of this blog entry is to give you a sense of what it is like to build apps with Durandal.
Installing Durandal
First things first. How do you get Durandal?
The GitHub project for Durandal is located here:
https://github.com/BlueSpire/Durandal
The Wiki — located at the GitHub project — contains all of the current documentation for Durandal. Currently, the documentation is a little sparse, but it is enough to get you started.
Instead of downloading the Durandal source from GitHub, a better option for getting started with Durandal is to install one of the Durandal NuGet packages.
I built the Movies App described in this blog entry by first creating a new ASP.NET MVC 4 Web Application with the Basic Template. Next, I executed the following command from the Package Manager Console:
Install-Package Durandal.StarterKit
As you can see from the screenshot of the Package Manager Console above, the Durandal Starter Kit package has several dependencies including:
· jQuery
· Knockout
· Sammy
· Twitter Bootstrap
The Durandal Starter Kit package includes a sample Durandal application. You can get to the Starter Kit app by navigating to the Durandal controller.
Unfortunately, when I first tried to run the Starter Kit app, I got an error because the Starter Kit is hard-coded to use a particular version of jQuery which is already out of date. You can fix this issue by modifying the App_Start\DurandalBundleConfig.cs file so it is jQuery version agnostic like this:
bundles.Add(
new ScriptBundle("~/scripts/vendor")
.Include("~/Scripts/jquery-{version}.js")
.Include("~/Scripts/knockout-{version}.js")
.Include("~/Scripts/sammy-{version}.js")
// .Include("~/Scripts/jquery-1.9.0.min.js")
// .Include("~/Scripts/knockout-2.2.1.js")
// .Include("~/Scripts/sammy-0.7.4.min.js")
.Include("~/Scripts/bootstrap.min.js")
);
The recommendation is that you create a Durandal app in a folder off your project root named App. The App folder in the Starter Kit contains the following subfolders and files:
· durandal – This folder contains the actual durandal JavaScript library.
· viewmodels – This folder contains all of your application’s view models.
· views – This folder contains all of your application’s views.
· main.js — This file contains all of the JavaScript startup code for your app including the client-side routing configuration.
· main-built.js – This file contains an optimized version of your application. You need to build this file by using the RequireJS optimizer (unfortunately, before you can run the optimizer, you must first install NodeJS).
For the purpose of this blog entry, I wanted to start from scratch when building the Movies app, so I deleted all of these files and folders except for the durandal folder which contains the durandal library.
Creating the ASP.NET MVC Controller and View
A Durandal app is built using a single server-side ASP.NET MVC controller and ASP.NET MVC view. A Durandal app is a Single Page App. When you navigate between pages, you are not navigating to new pages on the server. Instead, you are loading new virtual pages into the one-and-only-one server-side view.
For the Movies app, I created the following ASP.NET MVC Home controller:
public class HomeController : Controller {
public ActionResult Index() {
return View();
}
}
There is nothing special about the Home controller – it is as basic as it gets.
Next, I created the following server-side ASP.NET view. This is the one-and-only server-side view used by the Movies app:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div id="applicationHost">
Loading app....
</div>
@Scripts.Render("~/scripts/vendor")
<script type="text/javascript" src="~/App/durandal/amd/require.js"
data-main="/App/main"></script>
</body>
</html>
Notice that I set the Layout property for the view to the value null. If you neglect to do this, then the default ASP.NET MVC layout will be applied to the view and you will get the <!DOCTYPE> and opening and closing <html> tags twice.
Next, notice that the view contains a DIV element with the Id applicationHost. This marks the area where virtual pages are loaded. When you navigate from page to page in a Durandal app, HTML page fragments are retrieved from the server and stuck in the applicationHost DIV element.
Inside the applicationHost element, you can place any content which you want to display when a Durandal app is starting up. For example, you can create a fancy splash screen. I opted for simply displaying the text “Loading app…”:
Next, notice the view above includes a call to the Scripts.Render() helper. This helper renders out all of the JavaScript files required by the Durandal library such as jQuery and Knockout. Remember to fix the App_Start\DurandalBundleConfig.cs as described above or Durandal will attempt to load an old version of jQuery and throw a JavaScript exception and stop working.
Your application JavaScript code is not included in the scripts rendered by the Scripts.Render helper. Your application code is loaded dynamically by RequireJS with the help of the following SCRIPT element located at the bottom of the view:
<script type="text/javascript" src="~/App/durandal/amd/require.js"
data-main="/App/main"></script>
The data-main attribute on the SCRIPT element causes RequireJS to load your /app/main.js JavaScript file to kick-off your Durandal app.
Creating the Durandal Main.js File
The Durandal Main.js JavaScript file, located in your App folder, contains all of the code required to configure the behavior of Durandal. Here’s what the Main.js file looks like in the case of the Movies app:
require.config({
paths: {
'text': 'durandal/amd/text'
}
});
define(function (require) {
var app = require('durandal/app'),
viewLocator = require('durandal/viewLocator'),
system = require('durandal/system'),
router = require('durandal/plugins/router');
//>>excludeStart("build", true);
system.debug(true);
//>>excludeEnd("build");
app.start().then(function () {
//Replace 'viewmodels' in the moduleId with 'views' to locate the view.
//Look for partial views in a 'views' folder in the root.
viewLocator.useConvention();
//configure routing
router.useConvention();
router.mapNav("movies/show");
router.mapNav("movies/add");
router.mapNav("movies/details/:id");
app.adaptToDevice();
//Show the app by setting the root view model for our application with a transition.
app.setRoot('viewmodels/shell', 'entrance');
});
});
There are three important things to notice about the main.js file above. First, notice that it contains a section which enables debugging which looks like this:
//>>excludeStart(“build”, true);
system.debug(true);
//>>excludeEnd(“build”);
This code enables debugging for your Durandal app which is very useful when things go wrong. When you call system.debug(true), Durandal writes out debugging information to your browser JavaScript console. For example, you can use the debugging information to diagnose issues with your client-side routes:
(The funny looking //> symbols around the system.debug() call are RequireJS optimizer pragmas).
The main.js file is also the place where you configure your client-side routes. In the case of the Movies app, the main.js file is used to configure routes for three page: the movies show, add, and details pages.
//configure routing
router.useConvention();
router.mapNav("movies/show");
router.mapNav("movies/add");
router.mapNav("movies/details/:id");
The route for movie details includes a route parameter named id. Later, we will use the id parameter to lookup and display the details for the right movie.
Finally, the main.js file above contains the following line of code:
//Show the app by setting the root view model for our application with a transition.
app.setRoot('viewmodels/shell', 'entrance');
This line of code causes Durandal to load up a JavaScript file named shell.js and an HTML fragment named shell.html. I’ll discuss the shell in the next section.
Creating the Durandal Shell
You can think of the Durandal shell as the layout or master page for a Durandal app. The shell is where you put all of the content which you want to remain constant as a user navigates from virtual page to virtual page. For example, the shell is a great place to put your website logo and navigation links.
The Durandal shell is composed from two parts: a JavaScript file and an HTML file. Here’s what the HTML file looks like for the Movies app:
<h1>Movies App</h1>
<div class="container-fluid page-host">
<!--ko compose: {
model: router.activeItem, //wiring the router
afterCompose: router.afterCompose, //wiring the router
transition:'entrance', //use the 'entrance' transition when switching views
cacheViews:true //telling composition to keep views in the dom, and reuse them (only a good idea with singleton view models)
}--><!--/ko-->
</div>
And here is what the JavaScript file looks like:
define(function (require) {
var router = require('durandal/plugins/router');
return {
router: router,
activate: function () {
return router.activate('movies/show');
}
};
});
The JavaScript file contains the view model for the shell. This view model returns the Durandal router so you can access the list of configured routes from your shell.
Notice that the JavaScript file includes a function named activate(). This function loads the movies/show page as the first page in the Movies app. If you want to create a different default Durandal page, then pass the name of a different age to the router.activate() method.
Creating the Movies Show Page
Durandal pages are created out of a view model and a view. The view model contains all of the data and view logic required for the view. The view contains all of the HTML markup for rendering the view model.
Let’s start with the movies show page. The movies show page displays a list of movies. The view model for the show page looks like this:
define(function (require) {
var moviesRepository = require("repositories/moviesRepository");
return {
movies: ko.observable(),
activate: function() {
this.movies(moviesRepository.listMovies());
}
};
});
You create a view model by defining a new RequireJS module (see http://requirejs.org). You create a RequireJS module by placing all of your JavaScript code into an anonymous function passed to the RequireJS define() method.
A RequireJS module has two parts. You retrieve all of the modules which your module requires at the top of your module. The code above depends on another RequireJS module named repositories/moviesRepository.
Next, you return the implementation of your module. The code above returns a JavaScript object which contains a property named movies and a method named activate.
The activate() method is a magic method which Durandal calls whenever it activates your view model. Your view model is activated whenever you navigate to a page which uses it. In the code above, the activate() method is used to get the list of movies from the movies repository and assign the list to the view model movies property.
The HTML for the movies show page looks like this:
<table>
<thead>
<tr>
<th>Title</th><th>Director</th>
</tr>
</thead>
<tbody data-bind="foreach:movies">
<tr>
<td data-bind="text:title"></td>
<td data-bind="text:director"></td>
<td><a data-bind="attr:{href:'#/movies/details/'+id}">Details</a></td>
</tr>
</tbody>
</table>
<a href="#/movies/add">Add Movie</a>
Notice that this is an HTML fragment. This fragment will be stuffed into the page-host DIV element in the shell.html file which is stuffed, in turn, into the applicationHost DIV element in the server-side MVC view.
The HTML markup above contains data-bind attributes used by Knockout to display the list of movies (To learn more about Knockout, visit http://knockoutjs.com). The list of movies from the view model is displayed in an HTML table.
Notice that the page includes a link to a page for adding a new movie. The link uses the following URL which starts with a hash: #/movies/add. Because the link starts with a hash, clicking the link does not cause a request back to the server. Instead, you navigate to the movies/add page virtually.
Creating the Movies Add Page
The movies add page also consists of a view model and view. The add page enables you to add a new movie to the movie database.
Here’s the view model for the add page:
define(function (require) {
var app = require('durandal/app');
var router = require('durandal/plugins/router');
var moviesRepository = require("repositories/moviesRepository");
return {
movieToAdd: {
title: ko.observable(),
director: ko.observable()
},
activate: function () {
this.movieToAdd.title("");
this.movieToAdd.director("");
this._movieAdded = false;
},
canDeactivate: function () {
if (this._movieAdded == false) {
return app.showMessage('Are you sure you want to leave this page?', 'Navigate', ['Yes', 'No']);
} else {
return true;
}
},
addMovie: function () {
// Add movie to db
moviesRepository.addMovie(ko.toJS(this.movieToAdd));
// flag new movie
this._movieAdded = true;
// return to list of movies
router.navigateTo("#/movies/show");
}
};
});
The view model contains one property named movieToAdd which is bound to the add movie form. The view model also has the following three methods:
1. activate() – This method is called by Durandal when you navigate to the add movie page. The activate() method resets the add movie form by clearing out the movie title and director properties.
2. canDeactivate() – This method is called by Durandal when you attempt to navigate away from the add movie page. If you return false then navigation is cancelled.
3. addMovie() – This method executes when the add movie form is submitted. This code adds the new movie to the movie repository.
I really like the Durandal canDeactivate() method. In the code above, I use the canDeactivate() method to show a warning to a user if they navigate away from the add movie page – either by clicking the Cancel button or by hitting the browser back button – before submitting the add movie form:
The view for the add movie page looks like this:
<form data-bind="submit:addMovie">
<fieldset>
<legend>Add Movie</legend>
<div>
<label>
Title:
<input data-bind="value:movieToAdd.title" required />
</label>
</div>
<div>
<label>
Director:
<input data-bind="value:movieToAdd.director" required />
</label>
</div>
<div>
<input type="submit" value="Add" />
<a href="#/movies/show">Cancel</a>
</div>
</fieldset>
</form>
I am using Knockout to bind the movieToAdd property from the view model to the INPUT elements of the HTML form. Notice that the FORM element includes a data-bind attribute which invokes the addMovie() method from the view model when the HTML form is submitted.
Creating the Movies Details Page
You navigate to the movies details Page by clicking the Details link which appears next to each movie in the movies show page:
The Details links pass the movie ids to the details page:
#/movies/details/0
#/movies/details/1
#/movies/details/2
Here’s what the view model for the movies details page looks like:
define(function (require) {
var router = require('durandal/plugins/router');
var moviesRepository = require("repositories/moviesRepository");
return {
movieToShow: {
title: ko.observable(),
director: ko.observable()
},
activate: function (context) {
// Grab movie from repository
var movie = moviesRepository.getMovie(context.id);
// Add to view model
this.movieToShow.title(movie.title);
this.movieToShow.director(movie.director);
}
};
});
Notice that the view model activate() method accepts a parameter named context. You can take advantage of the context parameter to retrieve route parameters such as the movie Id.
In the code above, the context.id property is used to retrieve the correct movie from the movie repository and the movie is assigned to a property named movieToShow exposed by the view model.
The movie details view displays the movieToShow property by taking advantage of Knockout bindings:
<div>
<h2 data-bind="text:movieToShow.title"></h2>
directed by <span data-bind="text:movieToShow.director"></span>
</div>
Summary
The goal of this blog entry was to walkthrough building a simple Single Page App using Durandal and to get a feel for what it is like to use this library. I really like how Durandal stitches together Knockout, Sammy, and RequireJS and establishes patterns for using these libraries to build Single Page Apps.
Having a standard pattern which developers on a team can use to build new pages is super valuable. Once you get the hang of it, using Durandal to create new virtual pages is dead simple. Just define a new route, view model, and view and you are done.
I also appreciate the fact that Durandal did not attempt to re-invent the wheel and that Durandal leverages existing JavaScript libraries such as Knockout, RequireJS, and Sammy. These existing libraries are powerful libraries and I have already invested a considerable amount of time in learning how to use them. Durandal makes it easier to use these libraries together without losing any of their power.
Durandal has some additional interesting features which I have not had a chance to play with yet. For example, you can use the RequireJS optimizer to combine and minify all of a Durandal app’s code. Also, Durandal supports a way to create custom widgets (client-side controls) by composing widgets from a controller and view.
You can download the code for the Movies app by clicking the following link (this is a Visual Studio 2012 project):
Durandal Movie App