Monday, March 25, 2013

SPA with DurandalJS

DurandalJS is a client side java-script library which designed to make Single Page Applications(SPA). Durandal is built on jQuery, Knockout and RequireJS libs.

DurandalJS is using Asynchronous Module Definition (AMD) pattern by referring RequireJS. In my previous post I showed how to use RequireJS with MVC.
In this post I'll explain how to create simple Single Page Application using DurandalJS.

First create MVC internet application and install following NuGet packages.
  • Durandal
  • Durandal.Router
  • Durandal.Transitions
This will add some folders and required java-script files to the project. 
Now we need to create a view, for host the Single Page Application. So, add an Action for HomeController and related view page like below.
Add script references to view. Using data-main attribute, RequireJS will identify the location of Start up scripts. We must add a div container with an id of "applicationHost". That's the place Single Page Application going to be host.
Add views, viewmodels and main.js file in to App folder. 
main.js file contains start-up scripts. So we can configure Durandal in there. Change main.js file like below.
We can enable debugging by using system.debug(true); This debug function is cross browser support and it only log details, when debug is enabled.
DurandalJS will start application by using app.start(). We can configure for application specific conventions like routing and also configure for mobile devices in this script. Finally set application root. You can see in our Single Page Application there are two views. Student and Person. So I have map those views using DurandalJS router.
Next we need to add shell.js, which is the root module that we configured in the main.js file. In shell module we activate student view. That means in start up of application student view will be default.
In DurandalJS for each view-model there must be relevant view file. So add shell.html. In root page, we have two links for student and person views. Next we need to bind each active view using KnockoutJS.
Now all the configurations parts are done. So add relevant view-models and views for Student and Person. After that, folder structure must be like below.
Content of each view and view-models should be like below. 
Run the application and browse /Home/Demo.
You can find the source of this demo in GitHub.

1 comment:

  1. What is the best way in your opinion to access a js-library located in the scripts-folder with durandal? This folder is located in the same hierarchy like the app-folder. Do you specify something like this in your app/viewmodels/viewmodelX.js: define(['./../scripts/library.js'...?

    This seems awkward to me. I might missing some important point here. Thank you for clearification and for this great post too. Regards, Günther