Adventures in Angular Podcast and an AngularJS Oslo Meetup

Tuesday, November 18, 2014

Last month I did an interview with the Adventures in Angular podcast crew, you can listen here.

I also did a talk at the AngularJS Meetup in Oslo. You can watch the recoding here.

Both the podcast and the Meetup talks were loosely centered around using the next version of JavaScript with the current version of Angular.

In addition to all the syntax sugar in ES6, which makes JavaScript code more expressive, the new class keyword works well for building services and controllers in Angular. As an example, imagine you are building a Pong game, and need a service to control the left paddle and a second service for the right paddle. One paddle is controlled by the keyboard, the other by AI. This is a scenario where you might, if you are brave, consider inheritance, as long as the relationship stays simple.

(function(app) {

    class Paddle {
        constructor() {
            this.x = 0;
            this.y = 0;
        }

        startMoveDown() {
            this.y += 2;
        }

        stopMoveDown() {
            this.y -= 1;
        }

        startMoveUp() {
            this.y -= 2;
        }

        stopMoveUp() {
            this.y += 1;
        }
    }

    class LeftPaddle extends Paddle {
        constructor(keyboardHandler) {
            Paddle.call(this);
            this.x = 25;
            this.y = 100;
            keyboardHandler.onArrowUp(38, () => this.startMoveUp(), this.stopMoveUp());
            keyboardHandler.onArrowDown(40, () => this.startMoveDown(), this.stopMoveDown());
        }
    }

    class RightPaddle extends Paddle {
        constructor() {
            Paddle.call(this);
            this.x = 975;
            this.y = 300;
        }
    }

    app.service("leftPaddle", LeftPaddle);
    app.service("rightPaddle", RightPaddle);

}(angular.module("pong")));

The class constructor for controllers and services will be injectable, but you’ll want to use module.service to register service classes, and not module.factory, because only .service instantiates the service using new.


Comments
Comments are closed.

My Pluralsight Courses

K.Scott Allen OdeToCode by K. Scott Allen
What JavaScript Developers Should Know About ECMAScript 2015
The Podcast!