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.

expect(angular.isFunction(factory.get)
).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.

(function(){
    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 app.run. 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

.when("/editCusomter/:customerId")
  • * 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.

$location.replace(); 
// Removes current path from stack. Needed for back button to work properly.

$location.path(path); 
// 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.

Controllers

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.


Comments

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'

Interns: Taking off the training wheels

My intern team has been working for several weeks now on our new website. We have already completed one deployment to production and are finalizing our second one. We started with a plan to release often adding small bits of functionality as we go and so far that plan has been working really well. We already feel like we have accomplished a lot because we have completed many of our project's requirements and should easily be able to complete the rest giving us time to do even more than just the original requirements. One of the things I have had some difficulty balancing has been how much to lead the interns and how much to let them figure out on their own. In deciding what our team process should be and how we should allocate our time, I think it was important for me to do more leading. I saw some deficiencies in how we were currently working and brought up some ideas for how we could address them. We had moved into spending all our time just working through stories and did not

My idea for Hearthstone to add more deck slots

Recently someone asked the Blizzard developers for more slots for decks in the game Hearthstone. The response was that they are talking about it and looking into it, but no decision has been made yet. One of the concerns over adding deck slots is that it could complicate the UI for Hearthstone and make it more difficult for new players to understand. I have what I think would be a good solution to add more deck slots without increasing the learning curve for the game much if at all. First I would take a look at the current selection screen for starting to play a game. It defaults to showing the decks that are custom built by the player if they have any custom decks, and there is an option to page over to the basic decks. This basic deck screen is perfect for how I would change this process. Instead of having 2 pages of decks, 1 for basic and 1 for custom, you would just see the select a Hero screen. Then once you selected the Hero you wanted, you would see all of the decks that