Skip to main content

Training With Dan Whalin

I had a great opportunity this week to be a part of a training course given by Dan Whalin. The focus of the class was on AngularJS, JavaScript, and a little bit about TypeScript. I learned a ton during these few days and want to share some the key points that I took away.

First, Dan is a great teacher and presenter, if you have the chance to take one of his courses or see him at a conference, I would highly recommend doing so.

Day 1 JavaScript

Naming functions in JavaScript you should be consistent. A Good practice to follow is:
  • Anything that needs to be "newed" up should be Pascal Cased (Upper first)
  • If the item is static it should be camel cased (Lower first)
If you have a function that accepts many parameters, change it to only accept one object with properties for all of the parameters you will need. Then when calling the function you can call using an object literal. This prevent parameters from being passed in the wrong order. Since JavaScript is dynamic it also become easy to add more parameters.

Think in terms of Objects, not just functions. Just because everything in JavaScript is a function, doesn't mean that you can't treat them like Objects. Continue to use the knowledge you have of other languages and how you separate code into smaller pieces.

Inheritance in JavaScript.
  • Object.Prototype, the object's prototype is a pointer to prototype, not actual inheritance.
  • Function.prototype, same as object, points to Function.prototype.
  • Adding a function to the prototype keeps only 1 in memory, versus 1 for each instance of the function.
  • Prototypes are like a linked list or the Chain of Responsibility pattern. Each stop checks itself and then moves up the list until it either finds something that matches or reaches global.
Using prototypes will improve performance and increase reusability of your code.

Day 2 AngularJS Services

An idea that occurred to me was that if you are building different components in Angular and separating each into its own folder, you could create a readme file under each folder for that would be specific to that component.
  • Could contain details on things that should be refactored
  • Should contain details on dependencies and references
  • Living document of the component and what it does

If you are writing unit tests for Angular, you can write a test that will verify a function exists.

).toBe(true); // Test for function to exists

Example of setting up a factory in Angular. Biggest change from what I used to do is the var injectParams above the function definition and then the $inject below. This passes JSHint checks for objects being defined before they are used.

    var injectParams = ['$http'];
    function Factory($http){
        return {
            get: function(){}
    Factory.$inject = injectParams;

    angular.module('app').factory('Factory', Factory);

The main difference between a Factory and a Service is that a Factory should return a custom object, but in a Service the returned Function is the object.

Following naming conventions a Service should be camel cased because it should not be "newed" up.

For $http calls, success should only be used when it is the end of the road. If you need to do logic or data manipulation, you should be using the .then. The reason for this is that success happens immediately and if you need to do work on the returned data, you might have timing issues. From success you get the ready to go data, but from .then you have to unwrap the data.

An idea that came up is for components with many binding or properties being watched upon is to have 1 directive watching events within that component, and then have it update only the data that needs changed. This could reduce the amount of resources being consumed and make the component more responsive.

Day 3 AngularJS Routes and Controllers

  • $routeProvider.when => where to go when the route is hit.
  • $routeProvider.otherwise => what to do if no rules match.
.resolve allows for you to do work before routing.
  • Might be useful for roles or permissions. Call to server before letting the user get to the destination page.
  • Defines properties that are injected into the destination controller.
  • The property name on the destination controller needs to match the name in the .resolve.
  • Could do work in resolve before passing onto controller. .reject on the returned promise should stop the route from happening (also good for permissions).
There are a couple of different ways that you can make templates more efficient.

  • Can embed templates in script tags on html with id used as the templateUrl. That way the template is loaded with the original html call and no extra trip to the server is needed.
  • Can write to $templateCache in Would allow for templates to be saved in cache.
  • Gulp can wrote into $templateCache with a task. This loads all views into cache for you on build.

Per Dan, use Gulp if you aren't already using a JS builder and need to start using one.

Routes can use route parameters, like id

  • * can be used as wildcard to allow anything after the *.
  • ? will make the property optional.
use $routeParams in the destination controller to pull route parameters out of the URL. $routeChangeStart broadcast from rootscope allows for handling of changing routes. This is another area that permissions could be handled. Could also be useful for redirecting and back button.

Dan shared this piece of code with us:

var path = '/login' + $location.$$path; 
// $$path is where they want to go. Used as a redirect param in route.

// Removes current path from stack. Needed for back button to work properly.

// Redirects to new path

If you are using routes to redirect users and they are unable to use the back button to get where they came from, you probably need to add something like this to your redirecting. If the user wants to get to a specific page, but needs to login before you allow them to that page, they will go to the page they want, unauthenticated, and then be forwarded to login. Their back button stack now looks like this: homePage => editPage (unauthenticated) => loginPage. If the user hits the back button on the login page, they are not taken back to the home page that they think of as their last page, but instead taken to the editPage (unauthenticated), which then redirects them back to the loginPage. So this code removes that middle page from the stack, which allows the back button to end up on the home page as the user would want. It also appends the location they wanted to end up. You would need to setup some more routing logic to handle this, but it will allow for the user to be redirected to the editPage (now authenticated) after they login, which is where they wanted to go.


Using controllerAs allows for assignment of properties without injecting $scope, uses "this". This gets you closer in line to using ES6 type syntax. Will still need to inject $scope for watches or $on, anything not a defined property of the controller.

Scope Life Cycle

If you hit the digest cycle maximum of 10, then you are doing something wrong. The only reason you would see this error is if you had properties that kept changing each other back and forth. The digest cycle loops through all watches when anything in scope changes. Then continues to loop until nothing is left that changed.

On a scope, if you call $digest, it will work on the changes for just that scope. This could be handy for very specific edge cases, but if you are architecting your code you probably shouldn't need to use this. Look for a way to reorganize your scopes and bindings to be more efficient.

There are 3 levels of watches, each with a different level of specificity:
  • false is default: reference watch. watches for reference in memory to change. Fast and Efficient.
    • Checks by reference using ===
  • true: value or equality watch. watches for any value change in the item being watched. Slowest, but most precise.
    • Check by Equality using angular.equals()
  • watchCollection. More efficient than true, but less precise.
If you are using a watch with true, you should make sure you need it. A "true" watch does deep watching and could be a performance problem.

Instead of using watch you can use ng-change on any control with ng-model. Depending on what your needs are, this might be more performant.

ng-model-options can be used to set updateOn: 'blur' to trigger changes only on blur and not on keyup. This could come in useful for not firing off events every time a button is pressed, but instead when the user changes focus.

ng-pluralize will allow for changing wording when count is 1 versus many.

ng-repeat will render much faster if using track by anything. Lets Angular optimize some of the bindings. Check your ng-repeats and make sure you are using trackBy.


Popular posts from this blog

Converting a Large AngularJS Application to TypeScript Part 1

I work on a project that uses AngularJS heavily. Recently we wondered if using a preprocesser like CoffeeScript or TypeScript for our JavaScript would be beneficial. If our team is going to switch languages, we would need to be able to convert existing code over without much pain and we would have to find enough value in switching that it would be worth the conversion.

I had read an article that stated that because TypeScript is a SuperSet of JavaScript, you could convert a plain JavaScript file to TypeScript by changing the extension to .ts and not much else would need to change. I wanted to test out this claim, so I took a file that I was familiar with, an Angular Controller, and tried to convert it to TypeScript to see how much effort it would take and then try to figure out where we would benefit from using TypeScript.

This is what the controller JavaScript file looked like to start out with:
(function () { 'use strict'; angular .module('app') …

Converting a Large AngularJS Application to TypeScript Part 2

In part 1 I was able to take an Angular controller written in JavaScript and convert it to a TypeScript file while doing very little to change the code. In this post I am going to explore transitioning that same controller to actually use the features provided in TypeScript. This is how I left off my controller:
declare var angular: any; (function () { 'use strict'; var controller: any = function($scope){ ... } angular .module('app') .controller('controller', controller); controller.$inject = ["$scope"]; })();
While performing the translation from JavaScript to TypeScript, I would make sure at every step that the functionality I expected still worked, so if anything I did broke the system I would change it back and try again with another approach. Also if something seemed like it worked too easily, I would break it on purpose to make sure I wasn't getting a false result through browser caching a previously working fil…

Gamify TDD

I like it when things that would not normally be associated with games add concepts from games as a way to incentives you to accomplish things. Why simply go for a run if you can have an app that will track you and give you a gold star if you do better than you did the last time? Why go to the coffee shop that only gives you coffee if the other one will give you points that you can redeem for free drinks eventually?

I was recently introduced to CodeSchool, an online training system similar to PluralSight, it has video courses and challenges you can take to prove that you retained what the video taught. CodeSchool also adds badges and tracks to your learning, so as you complete a video and its challenges you get a badge. Complete a collection of courses within a specific discipline and you become a master of that discipline.

Some of these incentives are not tangible and really don't mean much in the real world, but they tend to work for me. If I start working towards a large goal a…