Using Grunt with DurandalJs/RequireJs

One of the things I have quickly learned when using DurandalJS is that most often when learning about how to do things within Durandal, the real answer is to look into either KnockoutJS or into RequireJS.

In my last project we used DurandalJS and I was very pleased. However, the one piece I wasn’t very satisfied with was using Weyland. Since I was unable to use server side bundling, I need some solutions.

When I started, I was looking for some help on this, and now that I have a solution in place, I wanted to share back what approach I took and what worked well for me.

I have created a gist that highlights the Gruntfile and the packages I used.   Additionally it includes the optional Visual Studio ‘post-build’ code that was used:

I hope this helps others out there as well!



Javascript Inheritance

I’m always looking for a good solid javascript inheritance approach that fully supports javascript prototypical inheritance.  The one I’m going to show today will use Object.create – so if you are supporting older browsers, you will want to make sure you have the es5-shim in your project (which I highly suggest having anyway!).

Let’s create a scenario, where we have base ‘Vehicle’ and we’ll show how to extend that with a ‘Car’ object.


function Vehicle(name) { = name;

Vehicle.prototype.getDescription = function(){

Vehicle.prototype.getType = function(){
return ” is a vehicle”;


function Car(name, model){, name); //this will inherit all the instance properties
this.model = model; //add additional instance properties

Car.prototype = Object.create(Vehicle.prototype);  //very important as we want to inherit the prototype properties as well!

Now let’s say that we want to override the getType call for Car:

Car.prototype.getType = function(){
return “this is a car!”;

We can also extend an existing base (aka super call)

Car.prototype.getDescription = function(){ + ” is my favorite car!”;

That covers prototype/javascript inheritance – again, if you are using IE8, etc… you will need the es5-shim as Object.Create isn’t supported!

Simple Dojo Example – require, declare (class), and modules

I’ve been exploring the Dojo Toolkit this weekend after looking at some examples that Cesium (Sandcastle example) ships with.  There are many good examples and tutorials on the Dojo website to get yourself familiar with Dojo and up to speed.  Dojo has been around for quite some time, but it’s evolved – at the time of this writing I’m using version 1.9.

I’m a fan of RequireJs  – so to see that Dojo is built upon the same AMD concept as RequireJs is quite intriguing to me!  RequireJs allows for better structured JavaScript using concepts such as ‘dependency injection’ that many OO programmers are aware of.

Let’s jump into an example of how to use Dojo!  My example is built on two dojo tutorials (Introduction to AMD Modules and Classy Javascript).  To keep things simple and interesting, I’m using NodeJS to run this sample.  (All the source code for this post can be pulled down from my github repository).

Just to get this out of the way – let’s get our environment setup.  If you haven’t already, make sure you have NodeJs installed.  Keep in mind, NodeJs isn’t required to actually run this code, you can use any web server.   Create a new directory – ie. ‘modules’ and then enter the command ‘npm install connect’.  Node Connect is a simple and quick way to fire up a web server.  You should now see a ‘node_modules’ directory inside our modules folder.  The next step is to create our server – created a server.js file in the modules folder.  The code should look like this:

var connect = require('connect');
console.log('server running on port 8080');

Node makes it quite easy to get up and running, so this should be enough for our web server!  Let’s move on to what we came here to do!

As mentioned above, you can get the source code from my github repo – but lets take a look at the project structure:


As you can see, I have a ‘app’ folder with two javascript files.  The index.html will contain the code to run our simple example.  Let’s take a look at our index.html file:

        <link rel="stylesheet" href="style.css" media="screen">
    dojoConfig = {
        async: true,
            name:"app", location:"/app"
        <script src="//"></script>
                    "app/counter", "app/logger"
                ], function(counter, Logger){
                var logger = new Logger();

As you can see, I’m supplying our main dojo.js file via CDN.  The next section here in the script tags is our application (normally I’d even have this code in a separate .js file – but for now this will suffice).  We wrap our code up in our ‘require’ statement.  The first part of this is an array of strings for each dependency our application has.  In this case, we have a dependency on ‘counter’ and ‘logger’ (we do not use ‘.js’ as this will make them non-AMD modules).  The function that follows matches our two dependencies and provides access to that code, ‘counter’ and ‘Logger’.  In this example we can see that one is a ‘static’ object whereas the other is an object we will create. As you can see, this helps keep our code rather clean, the rest of the code.

Let’s take a look at the ‘counter.js’ code first – as it’s the simplest to follow:

    var privateValue = 0;
    return {
        increment: function(){
        decrement: function(){
        getValue: function(){
            return privateValue;

Dojo provides some good structure for us to create our modules.  In this case, we are wrapping our code in a ‘define’ function which tells Dojo this is a module and will be accessible from our application.   Dojo will handle loading and injecting this module into our main application. 

The second module this application uses is our ‘logger.js’ file.  This code takes a next step by wrapping our code in an object, aka class:

    var privateValue = 0;
    return {
        increment: function(){
        decrement: function(){
        getValue: function(){
            return privateValue;

The define in this example has some additional dependencies.  All four of these dependencies comes from the dojo framework.  This really shows how modular dojo is and how easy it is to cleanly separate your apps concerns  (Initially when building this application, I had this code in the index.html, then refactored it out to keep the index.html code very clean!).

This code introduces a second concept – that of ‘declare’.  To understand and see how to use ‘declare’ – take a look at the Dojo ‘live docs’ definition.  This particular object will expose a ‘log’ function.  Other libraries try to mimic a ‘class’ definition (aka Typescript, Backbone, etc..) whereas I believe through Dojo’s ‘declare’ it’s more in line with how most people write javascript today.   Since we aren’t creating the object in this code nor returning an object literal, the ‘return declare’ will allow the caller to instantiate the object. 

The live docs link above to declare provides good documentation with several examples.  I appreciate the inheritance and mixin capabilities of declare.

This should wrap up this post – I hope to share more as I further explore using Dojo with Require.  If you have any questions or feedback please share!

(Just a side note: I’ve been using KnockoutJS on several applications and recommend taking a look at the DurandelJS framework that creates a RequireJS/AMD application structure around KnockoutJS – you can see the power of using RequireJs/AMD).

KnockoutJS & ASP.NET Mvc Partial View Loading

Recently I’ve needed to dynamically load ‘partial views’ that are bound to KnockoutJS view models.  The application is a single page app approach, composite application where I’m loading a particular view.

Retrieving the ‘partialView’ is rather simple with ASP.NET Mvc:


This is rather straightforward.   I make the call to retrieve the template with a jQuery ajax call:


I create my viewmodel, and my viewmodel has a property with the partialViewName defined – ie. self.partialViewName = “_SomePartialView”;

This works very well so far – I have some caching of the html partial, although I might remove this and just takes a more server side ‘get’ ‘varybyparam’ caching on the controller action.

Previously I had an approach like this:

<div data-bind=”with: myViewModel”>

Which I still believe works good for one or two scenarios – but the number of viewmodel objects (I have 20+ views here getting loaded) let me change my approach to more of a ‘load on demand’.  I’m pretty happy with this!

Update: one of my concerns that I meant to research and apply here is the impact of loading vm’s to the same dom node with applyBinding and memory leaks.

A good response to this on stack overflow:

So what I do for this is use the ko.cleanNode prior to re-applying this binding to the same node:


Simple Quick Git Common Actions

Create Branch:

Switch to a new branch:

git checkout -b branch-name

Shows the branch your on highlighted by *

git branch

Add files – marks any files to be added

git add .

Check-in changes

git commit -a -m “message”   //I always use the -a even with the git add . usage

Merge (to master)

switch back to the branch you want to merge to

git checkout master

specify the branch you want to merge from

git merge branch-name

optional – remove that branch

git branch -d branch-name

to completely abandon a branch:

git branch -D branch-name //only if you really screw things up

Revert – or rather we can still undo the changes easily by having Git check out the previous commit with the checkout command (and a -f flag to force overwriting the current changes):

git checkout -f


Extra Content


This is definite OT but to add a few bonus items :)

Initial creation (this assumes you setup heroku):

heroku create --stack cedar
git push heroku master
(if using rails: heroku run rake db:migrate)

Static Properties and Methods with Coffeescript

class Person
   @test: (input) ->
      return input
   @staticProperty : 10
   @get: ->
     return {name:'Steve'}
   nonStatic: ->
     return "non static"

console.log Person.test 'Hello World'  #result is 'Hello World'
console.log Person.get() #result is object
console.log Person.staticProperty   #result is 10

#console.log Person.nonStatic()  this is an error
person = new Person()
console.log person.nonStatic() #result is 'non static'

Should be fairly explanatory :)

KnockoutJs : Toggling CSS class

A common scenario with Javascript is toggling a set of elements based on the selected element add applying, removing css classes.  You’ll see this on menu items, etc… and in my case where we want to have styled ‘button’s instead of a radio list.

An example of this might be handling the selection of the button and then applying a class and removing any other classes, for example:

$(‘.year_item’).bind(‘click’, function(){

In my first attempt at such a toggle with knockoutjs, I followed a similiar route – calling back to my viewmodel :

setYear: function (year, event) {

The binding in the html looks like this:

<ul data-bind=”foreach: years”>
<li><input data-bind=”text: $data, click: $parent.setYear” type=’button’/></li>

This works fine.  However, I can do better – since KnockoutJs supports setting the CSS class on binding.

ie. <div data-bind="css: { profitWarning: currentProfit() < 0 }">

So let’s take this example and show how we can effectively toggle the CSS class based upon the value of the binding – using our example above:

<ul class=”bigButtons” data-bind=”foreach: years”>
<li><input data-bind=”text: $data, click: $parent.year, css:{selected_year: $parent.year() === $data}”  type=’button’/></li>

That is it.  No more function required in the viewmodel.  To understand what happens here is to understand the $parent.year click event.  Basically in KnockoutJs 2.0 by default $parent.year takes the $data property as a parameter.  The year binding is set, which in turn triggers the css selection on all the items reevaluating if it should have that CSS appended.

This has proved to be very terse and valuable in our UI.

Edit: I’ve put an example out on jsFiddle: