Tuesday, May 28, 2013

Trick question : Closures in Javascript

Closures are one of the most powerful features of the Javascript language. If there is one thing that makes JS so versatile, it has to be closures. But they can be tricky if you do not understand:
  1. Closures capture the variable not just its value.
  2. Scope only changes using functions in Javascript.
So the question, What does the following code print:

var funcs = [];
// Setup
for (var i = 0 ; i < 10 ; i++) {
    funcs.push(function () { console.log(i) });
}
// Call
for (var j = 0 ; j < funcs.length ; j++) {
    funcs[j]();
}

The intuitive answer is 0,1,2,3…9 . However that is not the case. This is because each function in setup captured the variable i and not its value. When the for loop finished the variable i has a value 10 and therefore all functions print out 10. You now understand what (1) means. 

Now let’s make these functions print 0,1,2,3…9. The solution would be to create a new variable within the scope of the for loop so that each function gets a new variable. Now the only way to create a new scope is using a function (2). Lets say you don't know this and try the following which will not work. It will print 9 instead of 10 however since that is the last value that gets assigned to foo:

// Clear
funcs = [];
// Setup
for (var i = 0 ; i < 10 ; i++) {
    var foo = i;
    funcs.push(function () {
        console.log(foo)
    });
}
// Call
for (var j = 0 ; j < funcs.length ; j++) {
    funcs[j]();
}

To fix this we use the concept of immediately executing functions i.e. we declare a function (to create a new scope) and immediately execute it (to fall into that scope). The following will work. :

// Clear
funcs = [];
// Setup
for (var i = 0 ; i < 10 ; i++) {
    (function () {
        var foo = i;
        funcs.push(function () {
            console.log(foo)
        });
    })();
}
// Call
for (var j = 0 ; j < funcs.length ; j++) {
    funcs[j]();
}

You now understand (2). You can find the code here : http://jsfiddle.net/basarat/U9brW/

As a aside you might think the following is a good idea (will not work as expected):

// Setup
for (var i = 0 ; i < 10 ; i++) {       
    funcs.push(function () {
        var foo = i;
        console.log(foo)
    });   
}

But it’s actually no different than (will not work as expected):

// Setup
for (var i = 0 ; i < 10 ; i++) {
    funcs.push(function () { console.log(i) });
}

Because the only variable that is captured by the function is still i from the outer scope.

Monday, May 27, 2013

Using Actions to clean up your code

I am a firm believer of DRY “If you are doing the same thing thrice, you are doing it wrong” . Within reasonable effort ofcourse.

So when I see code like this:

List<string> permissions = new List<string>();
// The ones we care about:
if (Session.HasPermissions(Permission.AdministrationSetPoints))
{
    permissions.Add(Permission.AdministrationSetPoints.ToString());
}
if (Session.HasPermissions(Permission.Administration))
{
    permissions.Add(Permission.Administration.ToString());
}

There is no wonder that I want there to be a function to abstract out the if conditions. But creating a new function at class level looks a bit dirty. Not only do you have a new function that is only called from one place but you need to pass in a ref argument (permissions list). Later on its unclear at first sight (without reading xml comments perhaps) why this new function was created. Additional constraints like making sure your private functions are at the end may increase the distance between your original function and this new function. 

Lucky for us C# 3.0 gave us an excellent solution with inline lambdas:

List<string> permissions = new List<string>();

Action<Permission> addPermission = (Permission p) =>
    {
        if(Session.HasPermissions(p))
            permissions.Add(p.ToString());                   
    };
           
// The ones we care about:
addPermission(Permission.AdministrationSetPoints);
addPermission(Permission.Administration);

Notice that:
  • the action (addPermission) does not need to be passed in the permissions object since the outer scope variable is available.
  • The function is declared closer to where it is used and you can tell at first look why it was created.


To be honest. For this I was inspired by JavaScript closures.

Thursday, May 23, 2013

Add Existing Item as Link in Visual Studio


It is a feature that is used very commonly for code sharing between project. But I could not find good screenshots to show someone so here they are.

Right lick project folder and select Add - Existing Item:


Now select your file and choose “Add As Link”


An additional useful option is Copy if newer:

Wednesday, May 22, 2013

Setup maxlength for strings in ASP.NET MVC

String length is an attribute available in the System.ComponentModel.DataAnnotations; namespace for your viewmodels. It sets up validation for max length e.g:

[StringLength(100, ErrorMessage = "Length must be less than or equal to 100")]

In html this will warn the user if the length exceeds 100. But if you want the html input to disallow the user to even type more than 100 characters then that functionality is not provided out of the box. You can use the attribute added to the html tag because of StringLength ie. data-val-length-max to add the maxlength attribute using one line of jquery:

$('[data-val-length-max]').each(function () { $(this).attr("maxlength", $(this).attr('data-val-length-max')); });

The maxlength attribute prevents the user from entering more characters than are allowed. This one line does it for all inputs that have this attribute setup in a view. 

Sunday, May 19, 2013

AngularJS + RequireJS

TypeScript has excellent support for AMD / RequireJS and you can see that over here

http://www.youtube.com/watch?v=4AGQpv0MKsA

Now that I am working on throwing AngularJS into the mix it feels a bit awkward to integrate AngularJS / RequireJS / TypeScript.

I've done it before and infact this presentation uses all three:
http://basarat.github.io/TypeScriptDeepDive/
It provides a great sample for you to experiment with if you need to (based on RequireJS + AngularJS seed project https://github.com/tnajdek/angular-requirejs-seed)

It becomes a lot less relevant when you do your bundling and minification on the server e.g. http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification . Let me explain.

There are two reasons behind organization of your script files.

First: 

Items that are declared in the global namespace are available before they are used.
e.g. $ should be available before your code runs e.g. even the init: 
Or for that matter angular should be available before you go on creating your modules. This is the area where RequireJS is still relevant when you use AngularJS. This is the area that can also be solved by ordering in your JS bundles.

Second:

Functions declared are called in order. AngularJS does this inherantly. Any module declaration / service declaration / scope declarations are just declarations. These are executed depending upon the order they are defined as a dependency. e.g

Directives controllers and services all get instantiated (using function calls) before the module gets instantiated. This is a region of overlap between RequireJS and AngularJS and if you are using Angular then RequireJS loses a bit of its charm.

Finally:

The final decision is of course up to you and you will have to make it for your project based on your requirements. If you are using a lot of script tags and don't have a server side alternative then yes, I feel requireJS is a must for you. Otherwise, not so much.

Additionally: 

The angular team itself depends on closure compiler to do its minification (confirmed fact) along with sourcemaps (my assumption) to do its debugging. So they can effectively use a single script tag since the ordering logic is maintained by the closure compiler. 





Saturday, May 11, 2013

NodeJS Debugging with WebStorm

WebStorm makes getting started with NodeJS a breeze. I made a short video tutorial to show this that you can check out on youtube http://www.youtube.com/watch?v=6bKsDoFj83o also embedded below:


Friday, May 10, 2013

Getting Started with NodeJS on Windows

NodeJS on windows has come a long way since the early days. Now windows is pretty much a first class citizen in node world. I did a quick video to show how to get started with NodeJS on windows:


Wednesday, May 8, 2013

TypeScript AMD with RequireJS

Using TypeScript files with RequireJS is incredibly simple. However using JS files that are not aware of RequireJS can be a bit tricky. Also mixing Typescript with JavaScript all along using RequireJS can use a bit more documentation. So ... I made a video. Check it out here: http://www.youtube.com/watch?v=4AGQpv0MKsA

Covers Using TypeScript with RequireJS, using a non RequireJS file with TypeScript when in the RequireJS mode and a RequireJS Module with TypeScript.

Sunday, May 5, 2013

Getting Started with GIT on Windows : SourceTree

Getting started with GIT on windows has never been easier thanks to the great folk at Atlassian that made SourceTree. That is the "ONLY" software you need to install. It is extremely straightforward but I thought I would take you through a screenshot tour anyways.

Note: I found no need to make any change in the program defaults. 
That is rare and shows the great work the developers have done. 

Start http://sourcetreeapp.com/

Launch:
Install:
Watch the installer be awesome and download all you need:

Enter your details. Configuring automatic line ending handling is really great for open source work since people can use Unix and Windows without hassling about line endings:
Leave Putty selected:

It will ask you for your putty files. Just click cancel if you don't have putty installed (I don't):
Click Finish:

When sourcetree starts it will ask you for a license. Don't worry, its free: 


Use Register Now and you will be all set: 

Now you are all setup to get cracking with git. Painless wasn't it? 

Load a repository from GitHub

Just copy the git https url of the repository: 
Click Clone in SourceTree: 
Paste in the URL, put in the destination and click clone: 

Watch the magic happen: 
And you are all set: 

Using git terminal

Source tree comes with git terminal integrated. I did not have to install any separate software to get this git awesomeness. Just click the terminal button and get cracking with bash awesomeness on windows: 

Further Reading: 

Saturday, May 4, 2013

Setting up duplicate view of image in Photoshop

When doing high quality color work this becomes sort of a necessity since my Dell U2711 color profile is simply awesome.

You can open a duplicate view of the same image using Window > Arrange > New window for as shown:


Then you can work directly on your lovely Cintiq and view the outcome on an even better monitor.

It also helps to give another perspective on what you working on.

Thursday, May 2, 2013

TypeScript Deep Dive

I recently gave an indepth advanced talk on TypeScript at Melbourne ALT.NET:
http://www.meetup.com/Melbourne-ALT-NET/events/115068682/

I had a lot of fun preparing the slides for this presentation. They are based on RevealJS / HTML. I addtionally strapped in TypeScript / Angular / RequireJS for my future talks.

You can find the slides here: https://github.com/basarat/TypeScriptDeepDive and I encourage you to use these in your own talks and contributions are appreciated.

Slides embedded here as well (click on slide to make active and press f to go fullscreen):