Tigraine

Daniel Hoelbling-Inzko talks about programming

Enable code coverage reports in create-react-app projects

create-react-app is a nice and easy way to bootstrap a new React.js project with some sane defaults and most of the tedious configuration required to enable Webpack building of Babeljs etc..

One thing I was missing from the generated configs though is how to output code coverage. Turns out it's rather simple - locate your package json and add the following line under scripts:

  {
    "coverage": "node scripts/test.js --env=jsdom --coverage"
  }

This way you can run yarn coverage or npm coverage and get a nicely formatted output with your coverage data. You can read more about the jest cli options in the docs

Filed under reactjs, testing, tools, javascript

Moving Ember.js Handlebars templates into the asset pipeline

I am a big believer in not starting out full throttle with things like ember-rails or other crazy asset-pipeline helpers when you have absolutely no clue what you are doing. So naturally when I did my first serious Ember.js application I just went with the basic Ember starter kit and dumped all my templates into script tags in the html.

Well, after getting the basics to work I decided to clean up the mess that was quickly becoming of the HTML and found the wonderful HandlebarsAssets gem that promises to compile Handlebars down to JavaScript and serve it through the Rails 3.1+ asset pipeline. After doing so I can say with confidence I managed to hit every single stumbling block along the way so I decided to write down where I went wrong. Hopefully this helps some other poor soul before he has to dive deep into the bowels of Ember like I had to :).

First step was to move the content of my script tags into a /templates folder inside my app/assets/javascripts and name them accordingly ('slots/create' goes into the file templates/slots/create.hbs etc). Don't forget to require the directory from your application.js manifest file.

Once done the Handlebars compilation part seemed to work perfectly. Only problem: Ember.js doesn't actually care for the contents of HandlebarsTemplates and will just silenlty ignore them. Instead Ember.js wants it's templates to be registered on Ember.TEMPLATES and even more annoying: It won't complain if a template is not registered correctly unless you turned the right arcane debug setting on (yay!)

To actually get Ember to tell you if your templates can't be found you have to turn on debugging through the Ember.Application.create call:

Ember.Application.create({
  LOG_TRANSITIONS: true
  DEBUG: true,
  LOG_VIEW_LOOKUPS: true  //the important part!
});

Now on to get the HandlebarsTemplates into Ember.TEMPLATES:

First I RTFM and HandlebarsAssets has Ember.js support built in, so to enable it you simply create a config/initializers/handlebars.rb file and put the following in:

if defined?(HandlebarsAssets)
   HandlebarsAssets::Config.ember = true
end

And if you did compile your templates before you'll see absolutely no change. Yes that's right, nothing will happen because HandlebarsAssets caches the template output in /tmp. So to actually see your Ember templates show up you'll have to do a rm -rf tmp/.

Hope this helps - I'm now off raising tickets and maybe fixing some of these stupidities.. There is just no real reason for this to be such a piss-poor experience.

Execute callback once multiple ajax requests finish with jQuery

I just stumbled upon the problem of having to load multiple resources during page initialization. During the initial load I wanted a way to prevent any animations and other fancy stuff from happening but rather only create the page as soon as possible.

Since I couldn't find any way in jQuery (there are no combined callbacks) I decided to implement this using the deferred promise concept jQuery 1.5 introduced.

Deferred basically means "I represent a ajax call that has happened or is happening - ask me about it and I'll tell you when it's done or was done already". So implementing my little wait functions was rather trivial:

I used CoffeeScript for this, but the resulting JavaScript is also quite readable and you can use that too.

What this does is provide you with the awkwardly named function waitForAjaxRequestsToComplete that takes one callback parameter and an array of jQuery promises. Once all promises succeed or fail the callback will be called and the first parameter will contain information about failures.

Sample usage:

waitForAjaxRequestsToComplete(function (info) {
  console.log("requests failed " + info.failures)
  console.log("requests succeeded " + info.successes)
  console.log(info.failed) //contains all failed promises
}, [ $.ajax(...), $.ajax(...), $.ajax(...) ]);

jQuery.validate and multiple forms on one page

I like generic, convention based approaches to infrastructure so in most of my projects you'll find something like this in the main javascript file:

$('form').validate();
There is only one slight problem: jQuery validate doesn't work like most jQuery plugins and won't operate on the matched set, but rather only on the first element.

So if you want to validate multiple forms you have to call each form individually through each

$('form').each(function () {
    $(this).validate();
});

jQuery.validate and Microsofts unobtrusive validation don't play well together

I was banging my head against the wall for more than three hours, reading jQuery.validate's code, trying to figure out why my supplied errorPlacement or highlight callbacks where not called.

The code in question looked perfectly fine and came pretty much straight out of the docs:

$('form').validate({
    debug: true,
    errorPlacement: function () {
        console.log("errorPlacement", this, arguments);
    },
    highlight: function () {
        console.log("highlight", this, arguments);
    },
    success: function () {
        console.log("success", this, arguments);
    }
});

As you can see I was still stuck in the "let's see what we can do from these callbacks" phase of implementing my own automatic validation scheme for a project. Guess what the above did? Nothing! And I mean really nothing. The validation worked as expected with my validation classes, but none of my callbacks got ever called (meanwhile supplied arguments like messages etc worked like a charm).

After 3 hours I finally came onto something when I couldn't find the validation classnames that where put on my elements inside the jQuery.validation code I was looking at. Turns out: Microsoft's jquery.validation.unobtrusive.js cripples jQuery.validation so that most of it's configuration options simply don't work any more. Neither with the $.validate.setDefaults() nor with the $('#element').validate() methods.

Needless to say that I almost broke into tears when my stuff was working fine once I removed the unobtrusive script from the page.

I do like the unobtrusive stuff - it serves it's purpose inside the MS MVC niche. But in this case I was not using unobtrusive on that form at all! So I simply did not expect the library to mess with jQuery.validate in any way as there was no unobtrusive validation stuff going on.

Localized Fullcalendar options

I usually try to avoid using too many jQuery plugins, especially for rather simple stuff like this. But displaying a calendar is pretty tricky (believe me - I wrote one using GDI+) and Fullcalendar has saved me countless hours so far.

One issue that cropped up now is that we needed our Fullcalendar to be localized in German. As with most things I came across so far, Fullcalendar already supports it - but the documentation is a bit cryptic on the issue so here is my localized options hash:

var localOptions = {
	buttonText: {
		today: 'Heute',
		month: 'Monat',
		day: 'Tag',
		week: 'Woche'
	},
	monthNames: ['Jänner','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
	monthNamesShort: ['Jän','Feb','Mär','Apr','Mai','Jun','Jul','Aug','Sept','Okt','Nov','Dez'],
	dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
	dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa']
}

$('#calendar').fullCalendar($.extend({ ... your options ... }, localOptions));

jQuery: Execute once animation finished

Good JavaScript almost forces you into learning async programming and jQuery animations is no different. Everything in jQuery supports callbacks because the stuff you do is in most cases done on the background while your script continues to run.

But as with most stuff, there are many ways of going about this:

Completed Callbacks

    $('#item').fadeOut('slow', function () {
        console.log('animation finished');
    });

The problem with this approach is that it gets rather tedious to queue stuff together if you want to do say three things in order.

Let's say you want to a fadeOut animation then add a cssClass, start another animation and once that one is finished remove the cssClass again. Using callbacks this looks rather ugly:

    $('#item').fadeOut('slow', function () {
        var foo = $('#foo');
        foo.addClass('myclass');
        $('#item2').fadeIn('slow', function () {
          foo.removeClasS('myclass');
        }
    });

As you can see, two nested callbacks is really not that readable and almost confusing.. That's why there is a better way to do this:

The fx Queue

jQuery uses a queue for all it's animations. That's the magic behind this nice syntax:

    $('#item').fadeIn().fadeOut();

If you run this code it will first fade the item in and only once it's completely visible it will start the fadeOut animation.

Problem with this is that it looks nice in it's syntax, but can't be mixed with the regular jQuery methods. Something like

$('#item').fadeIn().removeClass('active').fadeOut();
will not work simply because you removeClass will be executed instantly while fadeIn and fadeOut will be queued for later execution by the effects (fx) queue.

In that case you can hook into the queue yourself by using the .queue() method:

    $('#item').fadeIn().queue(function (next) {
        $(this).removeClass('active');
        next(); //Important to continue running the queue
    }).fadeOut();

Hope this helps!

Filed under javascript, jquery

What I've been up to

I just noticed that I started a new job almost half a year ago and didn’t mention it on my blog.

So it’s probably time I share what interesting stuff I’ve been doing lately.

New job

I now work for Life a software development company in Klagenfurt that’s situated inside the Lakeside Park. We focus on R&D in areas like ERP systems, natural language processing and other business solutions.

Although I still believe Lakeside Park is one of the ugliest buildings ever designed, from the inside it’s not that bad. It’s also located right next to the University, so I can attend courses in between work (a huge plus).

While I am mainly developing a CQRS-style business application I also did a lot of smaller projects for customers like WWF/AI.

CQRS

CQRS is a new architectural style coined by Greg Young that makes use of a few older patterns like Event Sourcing and CommandQuerySeparation as described by Fowler and Meyer. The style has been around for some time in the .NET space and Greg Young did a wonderful job of explaining it in a lot of screencasts and documentation he put up on his CQRS site.

The main idea behind CQRS is an eventually consistent architecture that does not rely on a big entity-relationship datamodel but rather on EventSourcing. EventSourcing means that you are storing every state transition inside your Domain as a distinct business event. So any model can be generated off this string of events that represents the currenct state. The benefit is rather huge because you can use heavily de-normalized models to read data from, while always issuing well-defined commands to mutate state.

I’ll blog on this in the future, but I strongly urge you to read up on cqrsinfo.com.

Still, it’s not an easy style to grasp and I had to let it sink for a few months before I could make heads or tails of it. In essence it’s so simple that you can explain it rather quickly, but it requires a pretty fundamental shift away from the CRUD style architecture you might be used to and finding out how to effectively work with this new “style” while being productive doing it takes some time.

Fortunately, just when I started to get into the right mindset for this way of working a project came in that required almost exactly the kind of traceability and flexibility Event Sourcing would give us, so I decided to go with a full CQRS stack.

CQRS in itself has worked out quite nicely so far. There is a lot of infrastructure I had to create, although fortunately Jonathan Oliver has created the EventStore project that at least spared me the work of rolling my own EventStorage system.

Since I’ll be working on this project for the rest of the year you can expect a few posts on the internals of the system and my thoughts on CQRS and eventual consistency in web applications.

JavaScript

Although I hate to admit it, I was always a web developer. I still suck at design as much as anyone else, but I was writing web applications all along, trying to convince myself that I was doing back-end stuff while hacking together the occasional HTML input form.

No more, I finally gave in and acknowledged the browser as the one platform I am probably targetting 80% of my work for, so I decided it’s time man up and really learn JavaScript.

I kind of knew JavaScript, it’s C based after all.. And I kind of knew my way around jQuery but never took the time to properly learn what makes this language so great.

So I got myself the brilliant book JavaScript: The Good Parts by Douglas Crockford and took a few nights to watch his great presentation Crockford on JavaScript that made a lot of things about the language clearer.

Funny thing: Right after I started getting a firm grasp around JavaScripts/EcmaScripts quirkyness I had to help out getting a project out the door that was entirely done in JavaScript as it was using the Sencha Touch JavaScript library to run on the iPad. (Note: ExtJS/Sencha are really incredibly ugly JavaScript frameworks – Use jQuery whereever possible)

Ruby and Rails

This goes hand in hand with the last point. After realizing that I’ll be doing MVC for a pretty long time I decided it’s time to really take another look at Rails and how it’s been doing while I was following ASP.NET MVC.

While I had looked at Rails earlier, I usually had given up trying to figure out how to install it on Windows and had just looked at the samples to conclude: “Same as .NET but with a bit of code-gen”

And oh boy was I wrong! While ASP.NET MVC really manages to get a lot of things right (at least for a MS framework), Rails3 is simply lightyears ahead.

And it’s not so much the core functionality I was usually looking at. It’s the subtle little things you don’t see in the samples but really learn to appreciate while working.

It’s the empty folders everywhere that give your code a very clean structure. Everything has it’s place.

And it’s the simplicity of it’s helper methods and little things like respond_to that are so incredibly hard and noisy to do in .NET land. Or the way helpers simply work whereas helpers in MVC usually make me want to tear my hair out (at least if you are working with dynamic models they simply fail).

Or another example of things that are simply there and nobody managed to get off the ground in 3 versions of .NET MVC is the asset bundling that’s been going on in Rails forever. Rails bundles all your javascript assets into one application.js file together to reduce browser load times, while .NET in MVC3 still references 2 seperate javascript library files in it’s default project template.

Rails is doing all the things right that I’ve been struggling with on the ASP.NET MVC platform for years whenever I was writing a simple business app, and it’s damn elegant all the way. It’s solving the CRUD application part so perfectly and with such simplicity that I am pretty sure I’ll be doing a lot of simpler applications in Rails in the future.

Vim and Visual Studio

Part of working with a lot of JavaScript is that you start to feel the limitations of Visual Studio as a JavaScript IDE. It’s simply inadequate and besides some syntax highlighting the whole editor simply falls down when writing JavaScript (not to mention the indentation screwups it does all the time).

So I ended up learning Vim and must say that I really enjoy it.

With the right plugins Vim is one hell of a powerful editor that does not require 600 mb of Ram and 40+ seconds to start up.

Having you editor boot in milliseconds instead of seconds has also had a huge impact on my work, and I have to say it annoys me every day when VS decides to hang up on me for 15 seconds only because I did hit save twice.

New home and cute mammals

I heard conclusive evidence that all blogposts are better with pictures of little furry mammals, so this one has to have them too.

To make that happen I moved into a new apartment with my Girlfriend and got myself two little baby cats that are called “Schrödinger” and “Marie Curie”.

Schrödinger:

schroedinger

Marie Curie:

curie

JavaScript scope and how to leverage it

Care to guess what this will output?

function() {
var x = 1;
	if (x < 5) {
		var y = 3;
	}
	console.log(y);
}

If you expect y to be undefined you fell for the same trap as everyone who comes from a more traditional background.

The output is of course y = 3

JavaScript has no block scope

I’d suggest you tattoo that on the inside of your eyelids since it’s so important to remember..

Whenever JavaScript behaves totally irrational for you, take a hard look at your code and make sure you are not using block scope like you would in most other languages.

But how does JavaScript scope then?

JavaScript is a really nice functional language someone threw a lot of Java ugliness on to make it appeal to the unwashed masses.

But at it’s core it remains this beautiful functional language, so naturally: JavaScript scopes by functions

And since functions are objects, you can leverage this scoping to create your own little hidden namespaces whenever you like.

(function () {
var x = 1;
}());
console.log(x); //undefined

Since functions in JavaScript are objects, you can define one and immediately call it afterwards, thus creating a block that hides everything inside from the outside. This becomes very important when you try to avoid naming collisions with other libraries when writing your business logic.

Since it’s advisable to group your logic, you can use the above function syntax to create objects with their own little shared namespace you can then call from your page:

var util = (function () { var x,y; //private variables nobody sees return { method1: function() { return x; }, method2: function() { return y; }, }; }());

util.method1() //returns value of x

Interesting here is that although we used a function to define util, since that function was executed right on the spot, util now points to the return value of that function. In this case an object with two methods on it.

And now things get weird: Closure.

If may strike you that at the time we call util.method1() the function that created util has already returned (a long time ago), so in theory we should not be able to access x and y.

But like it would with block-scope in a traditional language, JavaScript also looks at it’s parent scopes if it can’t resolve an identifier inside it’s current one.

And in functional scoping this means it has to look in it’s parent scope that is a already returned function.

In short: JavaScript keeps the scopes around as long as there are references to them, so even if a function returned in the past, it’s scope is still available to functions that can access it’s scope.

This also means you can do cool stuff like this function that allows another function to be executed exactly once:

var once = function ( fn ) { var callCount = 0; return function () { callCount += 1; if ( callCount > 1) { throw "Function can only be called once"; } fn(); }; };

var f = function() { alert("hi"); }; f = once(f); f(); f(); //this call will throw

Did I mention that programming JavaScript is totally addicting?

Filed under programmierung, javascript

My Photography business

Projects

dynamic css for .NET

Archives

more