Barbarian Meets Codingbarbarianmeetscoding

WebDev, UX & a Pinch of Fantasy

Learn TypeScript to Improve Your JavaScript

TypeScript is JavaScript for C# Developers. The CoffeeScript of .NETters. It is a superset of JavaScript that brings all the goodness of type-checking, classes, modules, lambda expressions and awesome tooling to the web front-end. Everything to make for a more productive and better JavaScript development experience.

Regardless of its many benefits, this brief article is not going to be a TypeScript tutorial nor a how-to. Instead, I will focus in the TypeScript feature that suprised me the most, the quality of the JavaScript generated by the TypeScript transcompiler and the transcompiler itself as a tool to learn JavaScript best practices.

Microsoft's TypeScript may be the best of the many JavaScript front ends. It seems to generate the most attractive code.

Before we start, note that you can try all article code samples yourself at the TypeScript playground as you read along, making modifications here and there to TypeScript and seeing how it reflects in JavaScript (notice also how the web-based text editor provides code autocompletion for you TypeScript, sweet!).

Screenshot of TypeScript playground

Let’s start with a class definition then:

// This is a TypeScript class definition
// It uses some syntactic sugar to declare and initialize public members
class Barbarian {
  constructor(public name: string, public weapon: string) {}
  attack() {
    return (
      this.name +
      ' enters a frenzy, wields his ' +
      this.weapon +
      ' and strikes the enemy.'
    )
  }
}
var conan = new Barbarian('conan', 'bastard sword')
conan.attack()

// It produces this JavaScript
var Barbarian = (function() {
  function Barbarian(name, weapon) {
    this.name = name
    this.weapon = weapon
  }
  Barbarian.prototype.attack = function() {
    return (
      this.name +
      ' enters a frenzy, wields his ' +
      this.weapon +
      ' and strikes the enemy.'
    )
  }
  return Barbarian
})()

var conan = new Barbarian('conan', 'bastard sword')
conan.attack()

As you can see in the example above, TypeScript does two interesting things when transcompiling classes:

  1. it produces an Immediately-Invoked Function Expression (IFFE pronounced iffy) that creates a new lexical scope to avoid polluting the global namespace.
  2. it defines the class methods in the Barbarian prototype, which basically means that all instances of Barbarian will reuse the same function (instead of each one its own function as it would have happened if we would have defined attack inside the Barbarian function).

A similar approach is used for modules:

// This is a TypeScript module definition
// It defines its API as exports

namespace Character {
  export class Barbarian {
    constructor(public name: string, public weapon: string) {}
    attack() {
      return (
        this.name +
        ' enters a frenzy, wields his ' +
        this.weapon +
        ' and strikes the enemy.'
      )
    }
  }
}

var conan = new Character.Barbarian('conan', 'sword')
conan.attack

// It produces this JavaScript
var Character
;(function(Character) {
  var Barbarian = (function() {
    function Barbarian(name, weapon) {
      this.name = name
      this.weapon = weapon
    }
    Barbarian.prototype.attack = function() {
      return (
        this.name +
        ' enters a frenzy, wields his ' +
        this.weapon +
        ' and strikes the enemy.'
      )
    }
    return Barbarian
  })()
  Character.Barbarian = Barbarian
})(Character || (Character = {}))

var conan = new Character.Barbarian('conan', 'sword')
conan.attack

In this case we use another IFFE to wrap the class definition and add it to the Character namespace. The Character namespace is, in turn, initialized if it did not exist before by using the Character || (Character = {}) expression, a common JavaScript construct to initialize variables to a default value.

Finally, whichever are the TypeScript constructs that we use (and we’ll see a lot of them in the next example), the JavaScript that is generated is completely clean and pristine. See it with your own eyes:

// ****\*\*****
// TypeScript
// ****\*\*****

module Character {
export interface ICharacter {
name: string;
weapon: string;
hp: number;
attack(ICharacter): void;
}

    export class Barbarian implements ICharacter {
        hp: number;
        constructor(public name: string, public weapon: string) {
            this.hp = 100;
        }
        attack(enemy: ICharacter) {
            console.log(this.name + " enters a frenzy, wields his "
                + this.weapon + " and strikes " + enemy.name);
        }
        attackMany(enemies: ICharacter[]) {
            console.log("moooob attack!!!!");
            enemies.forEach((e) => this.attack(e));
        }
    }

    export class Mob<T extends ICharacter> {
        theMob: ICharacter[];
        constructor() {
            this.theMob = [];
        }
        attack(enemy: ICharacter) {
            this.theMob.forEach((c) => c.attack(enemy))
        }
        add(dude: ICharacter) {
            this.theMob[this.theMob.length] = dude;
        }
    }

}

import Barbarian = Character.Barbarian;
import Mob = Character.Mob;

window.onload = () => {
var conan = new Barbarian("conan", "sword");
var krull = new Barbarian("krull", "axe");
conan.attack(krull);

    var logenNinefingers = new Barbarian("Logen", "bastard sword");
    var angryMob = new Mob<Barbarian>();
    angryMob.add(conan);
    angryMob.add(krull);
    angryMob.attack(logenNinefingers);

};

// ****\*\*****
// JavaScript
// ****\*\*****

var Character;
(function (Character) {
var Barbarian = (function () {
function Barbarian(name, weapon) {
this.name = name;
this.weapon = weapon;
this.hp = 100;
}
Barbarian.prototype.attack = function (enemy) {
console.log(this.name + " enters a frenzy, wields his " + this.weapon + " and strikes " + enemy.name);
};
Barbarian.prototype.attackMany = function (enemies) {
var \_this = this;
console.log("moooob attack!!!!");
enemies.forEach(function (e) {
return \_this.attack(e);
});
};
return Barbarian;
})();
Character.Barbarian = Barbarian;

    var Mob = (function () {
        function Mob() {
            this.theMob = [];
        }
        Mob.prototype.attack = function (enemy) {
            this.theMob.forEach(function (c) {
                return c.attack(enemy);
            });
        };
        Mob.prototype.add = function (dude) {
            this.theMob[this.theMob.length] = dude;
        };
        return Mob;
    })();
    Character.Mob = Mob;

})(Character || (Character = {}));

var Barbarian = Character.Barbarian;
var Mob = Character.Mob;

window.onload = function () {
var conan = new Barbarian("conan", "sword");
var krull = new Barbarian("krull", "axe");
conan.attack(krull);

    var logenNinefingers = new Barbarian("Logen", "bastard sword");
    var angryMob = new Mob();
    angryMob.add(conan);
    angryMob.add(krull);
    angryMob.attack(logenNinefingers);

};

If you want to know more about TypeScript here’s a great talk by the Helsbergnator (hell yeah! XD) from this past Build 2013:

This post was inspired by Stefan Ingvarsson “Introduction to TypeScript” session on our local .NET User group. If you are a .NET developer near Linköping (Sweden), come and join us on facebook or at swenug.se!! :).

SweNug logo

Back from Vacations

Hi everyone! Vacations are finished and I am back! I spent most of them visiting my family in Asturias and it was great! Lots of nice company, food, drinks and nature. I also did not touch a computer in 3 weeks, doing a little bit of life with the normal folk that surround us :) so I have come back to Sweden with a huge hunger for programming. Watch out! Good things are coming! :)

Malin and I on vacations in asturias

Barbaric June: Being Focused and Productive With ilPomodoro

Barbaric Monthly is my attempt at building/improving a coding project per month so that I can experiment with old and new technologies, learn ad infinitum, remain excited about the craft and nurture my passion for software development. This Barbaric Monthly is about practicing knockout.js building a web-based Pomodoro technique client: il Pomodoro.

Hello my fellow coders! Soon I’ll be going on vacation to a remote and undisclosed location for the next three weeks! Unfortunately I won’t have access to these beloved devices that we call computers, and least of all to the internetz, that’s why I thought it would be nice to write one last blog post before I step into the wilderness, perhaps, never to return - one never knows what prowls within the unknown :).

It has been a while since the last barbaric monthly since I have being mainly focusing in studying and getting my WebDev fu up to speed for my current job at medius. Although I haven’t really been working solely on any project in particular, I have tinkered on an off with il Pomodoro, a simple web based Pomodoro technique app written with knockout.js.

The project is in a very early stage providing the most basic functionality within the pomodoro technique: creating tasks, dividing them into pomodoros and a pomodoro timer. Check it out at www.barbarianmeetscoding.com/iPomodoro and GitHub.

screenshot of the il pomodoro web app

As I mentioned above, it is mainly written in knockout.js but it also uses require.js for AMD and jasmine as testing framework. You can see it as a little more advanced example than those of my barbarian meets knockout.js series.

And now it is time to say good bye. Have an awesome summer everyone!! :)

Barbaric Tip of the Week: Writing Consistent, Idiomatic JavaScript

Barbaric Tip of the Week is a weekly series whose main purpose is to share tiny bits of knowledge that I find specially useful and interesting.

Hello there! This week’s Barbaric Tip are just some resources to help you improve your JavaScript fu:

Neo learns JavaScript

Barbarian Meets Knockout: Knockout.js Observables

The “barbarian meets” series are a collection of articles that intend to introduce and explain useful libraries, frameworks, tools and technologies in simple and straightforward terms. These new series will focus on Knockout.js, the popular JavaScript MVVM library

Updated June 11th 2013 from the awesome comments by Maciej Makowski

I already used up the sensational introduction in the first blog post of these series so unfortunately I see myself forced to go straight down to business this time xD. In the last installment of these series we gave a short introduction to Knockout.js, what it is, why should you care and how to get started. In this blog post I will focus in one of the pillars of Knockout, the concept of observables, JavaScript objects that have the ability to notify others when they have been changed. Let’s get started.

Barbarian Meets Knockout

  1. Introduction to Knockout.js
  2. Knockout.js Observables
  3. Knockout.js Computed Observables
  4. Introduction to Knockout.js Observable Arrays

    1. Knockout.js Observable Arrays in Knockout 3.0
  5. Knockout.js Bindings
  6. Knockout.js Templating Engine
  7. Extending Knockout.js with Custom Bindings
  8. Inside the Source Code
  9. Scaling Knockout.js
  10. Knockout.js and SPAs (Single Page Applications)
  11. Persisting Data When Using Knockout.js in the Front End
  12. Using Knockout in an unobstrusive fashion
  13. The Bonus Chapters

Introducing the Example: The Pen&Paper RPG Inventory Screen

For this particular chapter, I have created this teeny tiny example that represents an inventory screen of our Pen&Paper RPG: Blood & Steel!! (I just started roaring while I was writing blood & steel - true story). Within it, the player will be able to drop items from the inventory freeing himself from unnecessary weight and the overstrained weakening status. Through the next sections, I will go disecting the example as I explain the concept of observables, and I will continue using it even in later chapters when I delve into computed observables and observable arrays. Here it is:

Check out this Pen!

Observables

Observables are JavaScript objects - to be more accurate they are functions as we will see later, but functions are objects in JavaScript so… well… :) - that have the ability to notify others when they have been changed. Thus allowing DOM elements to be updated and other programming constructs to perform operations in response to these changes. We create observables by using the ko.observable function:

// Model
var player = {
  name: "Kull",
  ...
}

// ViewModel
var PlayerViewModel = function() {
    var self = this;
    self.name = ko.observable(player.name); // Initialize the value of the observable to the name of the player
    ...
};

We then can read or update the observable easily by using a normal function notation:

var aPlayerViewModel = new PlayerViewModel()

var playerName = aPlayerViewModel.name() // read
aPlayerViewModel.name('John Doe') //write
aPlayerViewModel
  .name('John Doe')
  .characterClass('Barbarian')
  .race('Cimmenrian') // observables support function chaining

Whenever we change the value of the observable (name in this example), whichever construct that is listening will be notified. Notice, for example, how when you click on the Change Player Name Via Code in the example, the DOM element that is bound to the name observable is updated and reflects John Doe instead of Kull.

<div class="sidebar">
   <!-- this span is bound to the name property of the underlying view model -->
   <h2><span data-bind="text: name"></span>...</h2>
   ...
</div>
<!-- this button is bound to the changeName function, when clicked it will execute it -->
<btn class="btn btn-block" data-bind="click: changeName">Change Player Name Via Code</btn>
var PlayerViewModel = function() {
  ...
  self.changeName = function(){
    self.name("John Doe");
  };
};

Subscribing to Changes Within an Observable

You are not limited to use declarative bindings to bind DOM elements to your view Models. In addition to this standard way of binding, Knockout also provides support for explicitely subscribing to changes in an observable by using the subscribe method. In our example, I have written a simple mechanism to track changes in our ViewModel and activate a Save button.

<btn class="btn btn-large btn-block btn-primary" data-bind="click: saveChanges, visible: hasChanged">Save</btn>
var PlayerViewModel = function() {
  ...
  // change trancking system
  self.hasChanged = ko.observable(false);
  // this function below will be executed when the name is changed
  self.name.subscribe(function(newValue){
     self.hasChanged(true)
  });
  self.saveChanges = function(){
    // save changes
    self.hasChanged(false);
  }

Explicitly Triggering the Evaluation of Observables with ValueHasMutated

In certain scenarios, you will want to be able to trigger the evaluation of an observable, computed or observable array explicitly. You can achieve this by using the valueHasMutated function for any observable. Ryan Niemeyer has a great example on jsFiddle where he uses the valueHasMutated function to round a decimal input.

What Happens if I Do Not Use Observables?

The most simple binding scenario is that in which you bind your DOM elements to a vanilla JavaScript object. There is nothing wrong with this, knockout will pick those values and reflect them in your view. However, bear in mind that you will effectively have a one way, one time binding; that is, the value shown in your view will be read-only and if changed in the ViewModel, it will not be updated in the view.

Improving Knockout Readability with the Knockout-ES5 Plugin

At the point of this writing, Steven Sanderson has created a new plugin for knockout: knockout-es5. This new plugin allows you to abandon the function notation for reading/writing values from/to an observable in favor of using a more conventional and straightforward way of setting variables/properties:

// Let's say we have a simple system to spoil the player's food over time

// in classic knockout we would write
var latestConsumable = this.consumables()[this.consumables().length - 1] // Read a value
latestConsumable.isSpoiled(true) // Write a value

// whereas in knockout-es5 we would write
var latestConsumable = this.consumables[this.consumables.length - 1] // Read a value
latestConsumable.isSpoiled = true // Write a value

Steven Sanderson has written a sensational blog post - “Knockout-ES5: a plugin to simplify your syntax” - where you can learn a lot more about this new plugin.

A sneak peek inside the Source Code: Observables

As a final note on observables, I thought it would be both interesting and revealing to take a look at the actual Knockout.js source code. You can find the source code for observables under src/subscribables/observable.js. I have just selected the most juicy bits and left it untouched because it is pristine clear:

ko.observable = function(initialValue) {
  var _latestValue = initialValue

  function observable() {
    if (arguments.length > 0) {
      // Write

      // Ignore writes if the value hasn't changed
      if (
        !observable['equalityComparer'] ||
        !observable['equalityComparer'](_latestValue, arguments[0])
      ) {
        observable.valueWillMutate()
        _latestValue = arguments[0]
        if (DEBUG) observable._latestValue = _latestValue
        observable.valueHasMutated()
      }
      return this // Permits chained assignments
    } else {
      // Read
      ko.dependencyDetection.registerDependency(observable) // The caller only needs to be notified of changes if they did a "read" operation
      return _latestValue
    }
  }
  if (DEBUG) observable._latestValue = _latestValue
  ko.subscribable.call(observable)
  observable.peek = function() {
    return _latestValue
  }
  observable.valueHasMutated = function() {
    observable['notifySubscribers'](_latestValue)
  }
  observable.valueWillMutate = function() {
    observable['notifySubscribers'](_latestValue, 'beforeChange')
  }
  ko.utils.extend(observable, ko.observable['fn'])

  ko.exportProperty(observable, 'peek', observable.peek)
  ko.exportProperty(observable, 'valueHasMutated', observable.valueHasMutated)
  ko.exportProperty(observable, 'valueWillMutate', observable.valueWillMutate)

  return observable
}

Gotcha’s and Good Things to Know About Observables

Updated June 11th 2013

Knockout.js Always Notifies Observables When They Are Set To Objects

Before I mentioned how observables notify their subscribers when they are changed. Well… That is not entirely true. In reality, an observable will notify its subscribers:

  • when its value changes for primitive types (number, boolean, string and undefined) or,
  • always for object types.

See the implementation of equalityComparer and notice how it always returns false when the old value is an object:

// src/subscribables/observable.js
ko.observable['fn'] = {
  equalityComparer: function valuesArePrimitiveAndEqual(a, b) {
    var oldValueIsPrimitive = a === null || typeof a in primitiveTypes
    return oldValueIsPrimitive ? a === b : false
  },
}

Notice also the following test that documents that behavior:

// spec/observableBehaviors.js
it('Should notify subscribers of a change when an object value is written, even if it is identical to the old value', function() {
  // Because we can't tell whether something further down the object graph has changed, we regard
  // all objects as new values. To override this, set an "equalityComparer" callback
  var constantObject = {}
  var instance = new ko.observable(constantObject)
  var notifiedValues = []
  instance.subscribe(notifiedValues.push, notifiedValues)
  instance(constantObject)
  expect(notifiedValues).toEqual([constantObject])
})

And test this functionality in this fiddle written by Maciej.

If this behavior is not to your liking, know that you can provide your own custom implementation to equalityComparer.

Don’t Forget To Obliterate Your Manual Subscriptions

In certain scenarios (see example by Maciej below), a manual subscription will prevent your objects from being garbage collected, and thus create memory leaks (something that you are going to particularly want to avoid when writing SPAs):

function A() {
  var self = this
  self.observable1 = ko.observable()
}

function B(a) {
  var self = this

  self.observable2 = ko.observable()
  a.observable1.subscribe(function sync(newValue) {
    // this closure hold reference to "self" but is stored in "a.observable1"
    // so as long as "a" cannot be garbage collected, "self" won't be as well
    self.observable2(newValue)
  })
}

It is thus recommended to dispose these subscriptions when you no longer need them (again Maciej’s example):

function A() {
  var self = this
  self.observable1 = ko.observable()
}

function B(a) {
  var self = this

  self.observable2 = ko.observable()
  self.mySubscription = a.observable1.subscribe(function sync(newValue) {
    // this closure hold reference to "self" but is stored in "a.observable1"
    // so as long as "a" cannot be garbage collected, "self" won't be as well
    self.observable2(newValue)
  })

  self.dispose = function() {
    // this needs to be called when instance of B is no longer
    // needed
    self.mySubscription.dispose()
  }
}

Finally, this is what happens when you subscribe to an observable (I have removed some code for the sake of simplicity):

// src/subscribables/subscribables.js
ko.subscribable = function () {
    this._subscriptions = {};
    ...
}

ko.subscribable['fn'] = {
    subscribe: function (callback, callbackTarget, /*change*/ event) {
        ...
        var subscription = new ko.subscription(this, boundCallback, function () {
            // This callback is called when disposing a subscription
            ko.utils.arrayRemoveItem(this._subscriptions[event], subscription);
        }.bind(this));

        if (!this._subscriptions[event])
            this._subscriptions[event] = [];
        this._subscriptions[event].push(subscription);
        return subscription;
    },
    ...
}

ko.subscription.prototype.dispose = function () {
    this.isDisposed = true;
    this.disposeCallback();
};

Additional References

Conclusion

So! That was about it for Observables. I hope you now have a much clearer idea of what observables are, how they work and how you can take the most advantage of them. In the next chapter of these series I will be discussing computed observables. Have a good weekend! :)

Cheers!

P.S. I encourage you to look at the source code and the test suite. It can be very interesting and enlightening :)