Terrific 2.0.2 Changes

TerrificJS 2.0.2 is available. It can be download in a developer and minified version from www.terrifically.org.

The changes include useful enhancements. The list can be view on Github.

Register hook in the bootstrap

Until TerrificJS 2.0.1 there was no built-in way of finding out when all terrific modules have been initialised. With TerrificJS 2.0.2 there is an application.end event-hook. There’s an example below. The output can be viewed in the developer console.

Data for the fire-method’s default function

The default action of a module’s fire-method now also receives the data. There’s an example on the pull-request. Before version 2.0.2 the data was only sent to the receiving event handlers. There’s a simple example in the fiddle below and open your browser’s developer console to see the output:

Namespace for the module id

All registered modules receive an id, an index starting from 0 to n modules. Before the index was stored in “data-id”. Since this custom attribute could easily conflict with other libraries or frameworks the namespace terrific was introduced in 2.0.2. The id can be accessed in the module using this.id or this.$ctx.data('terrificId'). See ticket on Github for more details.

Register modules on root node in addModules

This enhancement was long overdue and I’m glad it’s finally integrated. A how-to for addModule can be found on terrifically.org.

Using TerrificJS with multiple versions of jQuery

This is a requirement I filed myself whilst working on a project that had multiple versions of jQuery included (legacy code). TerrificJS should use only the jQuery version I want it to which wasn’t possible without making changes to TerrificJS. All details can be found in the ticket on Github.

Context support for removeModules

The sandbox method addModules takes a node (context) as a parameter. It searches the context for any elements with a mod css class and initialises the module. addModules returns an array with the ids of all initialised modules. Until now removeModules required an array like this to remove modules. With terrific 2.0.2 removeModules can take the same parameter as addModules, making it a lot more useful. See the ticket on Github for more details.

Thanks to @brunschgi for the update.

Posted in javascript, terrific | Tagged , , , | Leave a comment

Terrific Quickstart, Lazyloading, Connectors and Tc.Config

I’ve been too busy to write posts for this blog but I did write a few how-to’s on TerrificJS a while ago. I published the how-to’s using github.io because I wanted to give that a try and play around with Jekyll.

The actual posts are:

Posted in javascript, terrific | Tagged , , , , , , | Leave a comment

Refactoring with Unit Tests

I saw the following function in the source of a larger web project and was immediately sceptical

$.helperArrayPos = function (array, value) {
    var i,
        l = array.length,
        num = -1;

    for (i = 0; i < l; i += 1) {

        if (array[i] === value) {
            num = i;
            i = l;

     return num;

The name of the function tells me that the position of an array is returned. The return num at the end of the function tells me that the returned value is a number type.
The function signature indicates that an array and a mixed value (probably string) are passed as arguments.  This lets me presume, that the mixed value (needle) is looked for in the array (haystack). If  the needle is found in the haystack, the position or index is returned, otherwise -1 in the case of needle not being found.

To be sure of what the function does, I wrote some unit tests. The reason for writing unit tests was to be sure of what $.helperArrayPos really does and to see if I couldn’t maybe replace it with jQuery’s $.inArray function, since jQuery was already included. I wrote the tests with QUnit.

test('$.helperArrayPos', function() {

    var haystack = [

    strictEqual($.helperArrayPos(haystack, 'apple'), 2);
    strictEqual($.helperArrayPos(haystack, 2), 4);
    strictEqual($.helperArrayPos(haystack, false), 5);
    strictEqual($.helperArrayPos(haystack, true), -1);


The above unit tests confirmed my concern $.helperArrayPos doing the exact same thing as $.inArray. I added further tests to underline my instincts to replace $.helperArrayPos.

strictEqual($.helperArrayPos(haystack, 'apple'), $.inArray('apple', haystack));
strictEqual($.helperArrayPos(haystack, 2), $.inArray(2, haystack));
strictEqual($.helperArrayPos(haystack, false), $.inArray(false, haystack));
strictEqual($.helperArrayPos(haystack, true), $.inArray(true, haystack));

After writing these tests I updated $.helperArrayPos to use $.inArray.

$.helperArrayPos = function (array, value) {
   return $.inArray(value, array);

I’m keeping the $.helperArrayPos function to avoid larger refactoring work at this time. I’ve reduced the code size a little keeping things DRY and I’m using a function ($.inArray) that is documented and tested by a reliable 3rd party (thank you jQuery).

Posted in frontend, javascript, testing | Tagged , , , | Leave a comment

Javascript Unit Testing and Why

Unit testing is a lot like exercising. Everyone knows it’s good, but very few do it or give up too early. Only those who stick with it and carry on learn to enjoy it.

I have been reading and learning a lot about testing for quite a while but in practice I always had excuses such as too little time, unit tests not being needed or worth the effort. The big ah ha came, when I realised that I don’t have to test everything and that a few tests are better than none. Another key factor that made testing a lot easier for me, is splitting and isolating business logic from ui logic. While ui logic is a pain to test, business logic is easy.

Why do I unit test?

Tests give me confidence. I know what works and what shouldn’t.

There’s nothing nicer than being 100% about something. I know my code works, because my tests tell me so.

Tests aid me in covering requirements

Requirements describe what a method should and shouldn’t do. Tests aid in applying those requirements. Writing test cases for requirements and then the function is easier than blindly writing a function that covers those requirements

Tests help me find flaws in my code

If something doesn’t work as it is supposed I create a test for it. If I have found the issue the test will fail. Also, if tests are green, than I know that the code that passes the tests is not the issue and that the issue lies somewhere else.

Unit tests are fast to create and fast to run

This is a given. If unit tests aren’t fast to run or easy to create, then you’re doing it wrong.

Tests reduce documentation effort

Each test case describes what a function can and cannot do. By looking at the test cases, it becomes clear what a function does.

Tests let me update code without worry

If I want to try anything out or test something I can do so without having to worry. If I break the code, the tests will let me know where. This also goes for changes anyone else makes without updating the tests.

Testing is fun

There’s something fun about testing the robustness of your own code. When writing tests you place yourself on the other side, as if you are playing chess against yourself. Writing tests that fail and then make them go green is rewarding.

What do I test?

Only my code

This is important. Don’t test what has been tested already. Don’t unit test ajax calls or event bindings done with a library such as jQuery. jQuery is already tested. This goes for most if not all the popular javascript frameworks and libraries.

As much of my code as possible

If I can test a function and it makes sense to, then I will, bearing in mind that it must be quick and easy.

Only what I can test easily and quickly

If test case seems complex and difficult then you’re doing it wrong. Remember to only test business logic and your code.

As little DOM as possible

Unit testing DOM (HTML) means using fixtures and creating slower tests. DOM manipulations are slower than testing function with simple input and output. Fixtures take time to create and they are not the real deal. If you do use fixtures remember that you are testing the code that uses the fixture and not the fixture. Fixtures need to modified if the actual widget/module/component is modified. For me a fixture is the minimum html required, to make javascript unit tests pass.

When do I test?

When ever I can

This is means when it’s easy to write a unit test and when I don’t have to refactor code to make it testable. If code isn’t testable but it works I leave it.

When modifying existing code

When I’m about to modify existing code that is testable I write a test or make sure there are tests. Any changes made with test coverage will highlight any breakage.

Before I write new code

This is what test driven development (tdd) is all about. First write tests, then write code. This sounds very easy, but it’s actually not until you get it. Once you get it, it’s easy.

When don’t I test?

When it’s too complicated

When writing a test seems to complicated or time consuming I stop and see if I can break up the function I want to test into smaller, simpler chunks, that I want to test.

When it’s not my code

I don’t test any code that I have not written or that has been tested already. This makes a lot of sense after reading, but it happens very quickly that you want to test code you don’t need to. Don’t test if the click event on a button fired – this goes especially if you’re using a library such as jQuery for your event bindings.

How do I test?

Divide and conquer

Split and isolate business logic from ui logic. Instead of using anonymous functions as event handlers, use named functions that can be tested.

I use QUnit

QUnit is only one of many testing frameworks. It’s lightweight and very easy to use compared to other frameworks. The QUnit cook book is very helpful and a good starting point.

I use one QUnit HTML page per javascript library that is tested.

A QUnit HTML page consists of

  • QUnit source
  • dependencies (such as jQuery)
  • library source to be tested
  • fixture, if needed
  • test cases

Write small functions instead of one big one

Small functions are easier to test. Many small functions also mean many small test cases which are also easier to write.

Write test cases for errors

If I find an error, I write a test case to confirm it. Then I fix my code and make the test pass.

Further reading

There is a ton of information online about unit testing in general and javascript testing libraries. Forget those for now and read Writing Testable JavaScript by Rebecca Murphey. Also have a look at http://qunitjs.com/cookbook/ and http://benalman.com/talks/unit-testing-qunit.html if you’re new to QUnit.

Posted in javascript, testing | Tagged , , | 2 Comments

The advantage of namespacing events

Until recently I have been creating custom events with jQuery (when using jQuery of course). Creating custom events in jQuery is done using .trigger (publish) and .on (subscribe). What I don’t like about .trigger and .on is that they require a node. While searching for a Publisher/Subscriber library I came across PubSubJS. I’m not going to explain how PubSubJS works. It is well documented and easy to use, if you have worked with custom events before. Like jQuery, PubSubJS allows for event namespacing. In the PubSub documentation this is referred to as hierarchical addressing.

Although I’m not new to the event namespacing concept, reading about it again gave me an idea (see Figure 1), which could be an aid in debugging and testing.

Figure 1: Contents of MyApp.Events.js

(function (w) {
    "use strict";
    w.MyApp = w.MyApp || {}; // Create global namespace "MyApp"

    var eventPrefix = 'myapp'; // Create event namespace

    // All events are global and stored as "constants"
    w.MyApp.Events = {
         START_LOCATION_SEARCH : eventPrefix + '.startlocationsearch',
         ANIMAL_SPOTTED : eventPrefix + '.animalspotted',
         UPDATE_MAP : eventPrefix + '.updatemap',
         LOCATION_FOUND : eventPrefix + '.locationfound',
         BOUNDS_CHECK : eventPrefix + '.boundscheck',
         FETCH_SPOTTINGS : eventPrefix + '.fetchspottings'

    PubSub.subscribe(eventPrefix, function (msg, data) {
        console.log('Event Log', msg);

Thanks to eventPrefix all events can be subscribed to with just one subscription. This makes monitoring the events very easy and aid in debugging.

Posted in javascript | Tagged , , , | Leave a comment

Learning Javascript

Besides HTML and CSS a frontend engineer must also be a master in javascript.

Learning and mastering

These are books I recommend. If you are new to javascript I would read in the following order:

  1. Eloquent Javascript (free online version) by Marijn Haverbeke
  2. Javascript Patterns by Stoyan Stefanov
  3. Javascript Design Patterns (free online) by Addy Osmani
  4. Javascript: The Good Parts by Douglas Crockford
  5. Javascript for Web Developers by Nicolas C. Zakas

The javascript bible

The ulitmate reference book to own is Javascript: Definitive Guide by David Flanagan. This book covers everything javascript has to offer.

Further reading

A javascript programmer is a software engineer and needs to know classic software engineering skill. It makes sense to read books such as HTTP: The Definitive Guide to improve your overall understanding of HTTP and how the world wide web works. Head First Design Patterns is a book usually read by java developers but I strongly recommend javascript developers to also read this. Design Patterns can be applied to any programming language with minor adjustments at most.


Reading and owning these books for re-reading is highly recommended. Reading alone is not enough though. It is important to practice theory by writing code, experimenting, creating bugs on the way and figuring out how these bugs were caused.

Post Update

21.05.2013: Add link to Addy Osmani’s Design Patter online book.

Posted in frontend, javascript | Tagged , , , | Leave a comment

How to chose a javascript library

There are so many free 3rd party libraries out there that are able to solve a problem. The question is which of these libraries to pick for the job.

Identifying reliable libary

How to chose a 3rd party library and make sure it’s reliable. The focus lies on libraries that are free to use.

  • The library’s source code is on a public repository such as Github.
  • The library is top ranking in search results. This means the library has been linked to often, perhaps from blogs where it has also been discussed.
  • There are questions and answers on Stackoverflow. Questions will arise if the library is used.
  • There are independent blog posts about the library. Only worthwhile libraries will be spoken about.

Github helps

Github makes identifying reliable libraries very easy. At the time of writing Javascript makes 21% of Github’s hosted source code, so it is very likely, that a javascript library is hosted on Github.

Have a look at the screenshot in Listing 1. There are three marked areas:

  1. Stars. The more the better. Only a reliable library’s repository will be favourited often.
  2. Forks. The more the better. Only a promising or otherwise interesting library’s repository will be forked to work on. More forks means more people are working on improving the library.
  3. Last update. The more recent the better. Recent updates means the library’s repository is alive and probably well kept.

Listing 1: jQuery-Mobile on Github (2013-05-12 20:15:15)

Other things to look at are tests. A folder named test in the repository’s root directory is a good sign. Tests provide confidence. A detailed documentation with examples and usage instructions is also a sign of a popular library. The author wouldn’t make this effort, if the library wasn’t meant for re-use.


Avoid re-inventing the wheel at all costs. If there are libraries out there then use them, but be careful about which library to use. The wise web developer will take some time in selecting a reliable library. He will do this eagerly because he is lazy and because he is aware of the price of using a poorly maintained library or creating an own one.

Posted in frontend, javascript | Tagged , , , , | Leave a comment

GIT Release Package Zip

On one of the projects I worked on previously I could develop a module independently. I had to develop independently for security reasons. This meant I had to use separate versioning for my code. I chose GIT. I prefer GIT to SVN for a few reasons.

This also meant that I had to hand over my module to the rest of the development team. The handover was a Zip-File containing my work. So how did I manage my handover packages?

Creating a Tag in GIT

When I was ready for the handover I made sure I was on the master branch and all the working features were merged with the master branch. The steps after that are described

1. Created a tag with a comment

git tag -a Release-YYYYMMDD -m 'Customer preview release'

2. Push tag to the remote branch

git push --tags

Creating a Zip with GIT

1. Create zip-archive for the handover

git archive --format zip --output /PathTo/Release/Release-YYYYMMDD.zip master

Don’t forget the branch name master at the end.

2. Create a simple release documentation
To monitor the changes I also included a list of the files that had actually changed between two releases. There’s a nice handy git-command to do this.

Get all changes between two commits (use commit hashes):

git diff --name-only d20354c d6070d48

That’s it already!

Posted in git, quicktip | Tagged , | Leave a comment

JSP Basics for Frontend Engineers

I am working on a website that uses Day CQ5.5 as it’s backend. Frontend engineers and CQ specialists are required to work closely together. This means that frontend engineers are writing html surrounded by jsp-logic. There are three useful reference links that make working with jsp a lot easier. A frontend engineer should be familiar with the basics and not run to the java software engineers for every little change.

The two useful links are:

Posted in quicktip | Tagged , , , , | Leave a comment

Energy consumption in Switzerland 1910 – 2010

I was randomly browsing the Swiss Government’s statistic site bfs.admin.ch and came across an excel sheet showing Switzerland’s total energy consumption from 1910 until 2010. There are many interesting bits and pieces of information in this spreadsheet for example:

  • Why did the total energy consumption suddenly drop in 1917? (There’s also a drop after 1943)
  • Why was more coal used from 1980 until 1991 and less before and after this period?
  • The usage of renewable energy from 1990 onwards
  • and so on…

10 times increase

In my opinion the most notable information is the increase in energy consumption from 1910 until 2010.

  • 1910 – 99’990 Terajoules
  • 2010 – 911’550 Terajoules

That’s roughly 10 times more in 2010. Obviously one needs to consider factors such as population growth, modern transportation and technology to make a solid statement about the consumption increase.

To give you an idea how many energy that is:

1 Terajoule = 277’777,778 kWh.

An average Swiss household consumes 3’500 kWh per year (2007), (Source [1]). I’ll let you do the math.


[1] Der typische Haushalt-Stromverbrauch, Jürg Nipkow, Stefan Gasser, Eric Bush, Bulletin SEV/VSE 19/2007

Posted in open data | Tagged , , , , , , | Leave a comment