Category Archives: JavaScript

JavaScript’s Gulf of Evaluation and Gulf of Execution

<rant>

It came to me yesterday why JavaScript development is such slow going for me. I think it’s because it feels like an OO language, but it’s really not. Particularly when using TypeScript, there are classes, ‘this’, inheritance, etc. The thing is that all these ‘artifacts’, for lack of a better term have been added to the language and aren’t there natively. That means that often, things that would behave as I expect them in a more ‘native’ OO language like Java (or Actionscript for that matter) don’t behave intuitively in JS. This means more time in the debugger saying things like “why isn’t that working?”.

Don Norman describes this as the Gulf of Evaluation and the Gulf of Execution. His canonical example is the settings for his freezer. Unless you know what the controls are affecting behind the panel, the odds of getting the temperature correct in the setup he describes are essentially random.

Now, consider probably the most canonical of the JS quirks, the behavior of this. It has scope only in the current function. Nest a function within a function and the scope of the parent ‘object’ doesn’t exist in the parent’s function. This is because in reality, there is no parent object, just a hierarchy of functions. But we have closure, so by setting ‘self = this’ in the parent, we get an approximation of the desired behavior. And now with fat arrow notation, this can indeed be nested (but Typescript won’t let you inherit a fat arrow method). But you have to know that, just like the mechanism behind the panel of Don Norman’s freezer.

The most recent thing that I had to deal with was the assembly of a hierarchical data provider object from a set of database calls. The structure is pretty straightforward:

dataProvider = {
    items:{
        type1:{
            item1:{...},
            item2:{...}
        },
        type2{
            item1:{...},
            item2:{...}
        },
        ....
    },
    associations:{[{...},{...},{...},...]}
}

I really thought I should be able declare these items on the fly, something like:

dataProvider = {};
dataProvider['items']['type']['item1'] = {...};
dataProvider['items']['type']['item2'] = {...};
dataProvider['associations'] = [];
dataProvider['associations'].push({...});
etc.

Instead, the ‘item1’ object gets created, but the [‘items’] object does not. I expected construction of the object to chain from tail to head like it does with execution (e.g. foo.bar().baz().etc). Instead I get a null object error, and a “why isn’t that working?” moment.

In the end, I had to write some code that created the original object and then before each item was added, to make sure that the appropriate property existed, otherwise create it and add it. So, instead of an hour or so of casual coding, this simple task mushroomed into an afternoon’s worth of careful development and testing.

Interestingly, I had to pick up PHP after a long absence, and for me at least, it behaves the way I expect OO languages to behave, with very consistent quirks that you have to learn once – I’m looking at you __construct()

So that’s why JS development takes too freakin’ long for my calcified OOP brain. But it’s also about why we should also be very careful when we try to make something look like something it’s not.

</rant>

Gotchas or Special Cases?

I’ve now been working in AngularTypeScript for a while, a few things have cropped up that are probably worth mentioning. Some things are just for clarity, others are because they had me confused for a while.

So without further adieu, my laundry list:

Structuring the main angular app class

I’ve decided that I like using the constructor, rather than instantiating the object and then calling a method. Mostly this is because in TypeScript, the arguments to the constructor aren’t defined in interfaces so it can vary naturally, and because it’s a bit less typing for the same result. Here’s the app I’m currently working on:

module AngularApp {
   // define how this application assembles.

   class QueryMain {
        serviceModule:ng.IModule;
        appModule:ng.IModule;

        constructor(angular:ng.IAngularStatic,
                        queryServicePtr:Function,
                        queryDirectivePtr:Function,
                        glNetDirectivePtr:Function,
                        infoDialogDirectivePtr:Function,
                        queryControllerPtr:Function){

            this.serviceModule = angular.module('phpConnection', []);
            this.serviceModule.service('QueryService', ['$http', queryServicePtr]);

            this.appModule = angular.module('rssApp', ['phpConnection', 'ngSanitize']);
            this.appModule.controller('MainCtrl', ['QueryService', '$timeout','$rootScope', queryControllerPtr]);
            this.appModule.directive('ngFeedPanel', ['$timeout','$rootScope', queryDirectivePtr]);
            this.appModule.directive('ngInfoDialog', ['$timeout','$rootScope', infoDialogDirectivePtr]);
            this.appModule.directive('ngNetworkWebgl', ['$timeout','$rootScope', glNetDirectivePtr]);
        }
   }


   // instantiate Angular with the components defined in the other files. Note
    // that weird things may happen with transclusion?

    new QueryMain(
        angular,
        PhpConnectionService.UrlAccess,
        new RssAppDirectives.ngFeedPanel().ctor,
        new WGLA2_dirtv.ngNetworkWebgl().ctor,
        new WGLA2_dirtv.ngInfoDialog().ctor,
        RssControllersModule.RssController
    )
}

There are really three patterns to note here. The first is that everything is that everything that the class QueryMain uses is passed in. No globals. And going along with that, please note that directives (and factories) have to be instantiated, so we pass in a pointer to a ctor() function, rather than the class as a whole. The last thing to mention is that there is no chaining. The modules are declared and then the components are added on individually rather than module().directive.controller() etc. The reason for this is that if you happen to declare, for example, a service that is needed by some later item. That service will not be visible if it’s chained with the declaration of the item. Line by line declarations appear to have more predictable results.

The wonderfulness of interfaces and a revisit of fatArrow = ():notation => {}

There seem to be times when it’s nicer to use fat arrow notation. In my experience, this pops up the most often in directives, though it can show up in promises as well. I’ve had some odd experiences where it seemed that ‘this’ doesn’t survive scope/closure changes into a called method. I can’t find any examples where I wasn’t able to make it work with conventional notation, but it’s worth covering anyway.

Since I’ve been working more with directives recently, we’ll use one of the directives used in the above code as an example. This one has had parts stripped out for clarity. By the way, as with every other class that is an Angular/Typescript component this extends my ATSBase class, which is covered here. :

export class ngFeedPanel extends NovettaUtils.ATSBase {
    private myDirective:ng.IDirective;
    private cobj:RssControllersModule.ICallbackPointers;

    constructor() {
        super();
    }
    private linkFn (scope:any, element:any, attrs:any) {
        this.cobj = scope.callbackObj;

        scope.nlpQuery = ():void => {
            var mobj:RssControllersModule.IDataResponse = scope.messageObj;
            this.cobj.setQueryString("");
            this.cobj.nlpQuery(mobj);
        };
    }

    public ctor(timeout:ng.ITimeoutService, rootscope:ng.IScope):ng.IDirective {

        if (!this.myDirective) {
            this.myDirective = {
                templateUrl: 'directives/rssFeed.html',
                restrict: 'AE',
                scope: {
                    messageObj: '=',
                    callbackObj: '='
                },
                link: this.linkFn
            }
        }
        return this.myDirective;
    }
}

If you’ve read any earlier posts, you’ll know that I like pointers. The ctor() method is used as a function pointer in the main app, and in turn the link: element of the ng.IDirective object points to the linkFn() method in this class.

Unlike interfaces for other languages, I’ve found interfaces most useful for handling the pattern of:

myObj = {
    thing1 : "thing1",
    thing2 : "thing2",
    thing3 : "thing3",
    thing4 : "thing4"
};

I hate those things. I’ll make some typo and not notice until the browser crashes in a test. And because there is often no context, I’ll look at the broken code and not see the problem (thingOne, not thing1, or something like that)

Typescript makes sure that doesn’t happen. This interface:

export interface ICallbackPointers{
    setQueryString : Function;
    addToQueryString : Function;
    rssQuery : Function;
    nlpQuery : Function;
}

Gets declared as a typed object:

export class RssController extends WGLA2_ctrl.Network3DCtrl{
   public callbacks:ICallbackPointers;
   ...

Instanced in the constructor (function pointers!):

this.callbacks = {
    setQueryString : this.setQueryString,
    addToQueryString : this.addToQueryString,
    rssQuery : this.googleNewsSubmit,
    nlpQuery : this.nlpQuerySubmit
};

Passed through the html:

<div class="resultsWrapper">
    <div ng-repeat="item in mc.itemDataArray track by $index">
        <ng-feed-panel message-obj="item" callback-obj="mc.callbacks"></ng-feed-panel>
    </div>
</div>

And used in the directive (also shown above as part of the linkFn()):

scope.nlpQuery = ():void => {
    var mobj:RssControllersModule.IDataResponse = scope.messageObj;
    this.cobj.setQueryString("");
    this.cobj.nlpQuery(mobj);
};

Never a chance for a mistake, but with all the power of ad-hoc object creation. Very cool.

Fat Arrow has been more mysterious. In the following I show two sets of code that use a service to get data from a source. In the fist example all the code is contained within a single class that extends ATSBase, which creates a fat arrow alias for each method. Nonetheless, without fat arrow, ‘this’ does not track back to the class:

public promiseCaller():void{
   this.promise = this.service.getQueries();
   this.promise.then(this.processData, this.errorData);
}

public processData = (data:any):void => {
   // 'this' is out of scope without fat arrow
   console.log("got data");
};

public errorData = (data:any):void => {
   // 'this' is out of scope without fat arrow
   alert("error getting data");
};

However, in the version shown below, ‘this’ is preservedwithin goodUserQuery() and errorResponse.

private goodUserQuery (response:any) {console.log("got data");}
private errorResponse (response:any) {alert("error getting data");}
public promiseCaller():void{
    this.queryService.submit(qstr, this.goodUserQuery, this.errorResponse);
}

It’s even preserved in the call to the queryService.submit call that takes place in a different service class, part of which is shown below:

public submit(query:string, goodResponse:any, errorResponse:any):any {
   return this.httpService(query).then(goodResponse, errorResponse);
}

So that’s odd.

The safe pattern appears to be that for small methods that I’m unlikely to extend, I’ll use fat arrow. Wrapping methods will extend just fine and will use the fat arrow functions inside. But I wouldn’t be able to extend the inner methods. Mostly, I think that’s fine and more likely to keep me out of trouble then accidentally typing ‘this’ when I should’ve typed ‘self’. So you basically have the choice:

scope.handleButtonPressFat = (strVal:string):void => {
   this.handleButtonPress(scope, strVal);
};
scope.handleButtonPress = function(strVal:string):void {
   self.handleButtonPress(scope, strVal);
};

But if you find yourself in a function that has been called out of a promise and closure isn’t working the way you think it should, try seeing if it can be fixed by using fat arrow.

TypeScript and AngularJS Unification?

Because of certain obscure reasons, AngularJS needs to do very particular things with “this”. Shortly after taking up TypeScript and trying to feed in Angular ‘objects’, I learned about how “Fat Arrow Notation” (FAN) allows for a clean interface with Angular. It’s covered in earlier posts, but the essence is

// Module that uses the angular controller, directive, factory and service defined above.
module AngularApp {
   // define how this application assembles.
   class AngularMain {
      serviceModule:ng.IModule;
      appModule:ng.IModule;

      public doCreate(angular:ng.IAngularStatic, tcontroller:Function, tservice:Function, tfactory:Function, tdirective:Function) {
         this.serviceModule = angular.module('globalsApp', [])
            .factory('GlobalsFactory', [tfactory])
            .service('GlobalsService', [tservice]);

         this.appModule = angular.module('simpleApp', ['globalsApp'])
            .controller('MainCtrl', ['GlobalsFactory', 'GlobalsService', '$timeout', tcontroller])
            .directive('testWidget', ['GlobalsService', tdirective]);
      }
   }
   // instantiate Angular with the components defined in the 'InheritApp' module above. Note that the directive and the factory
   // have to be instantiated before use.
   new AngularMain().doCreate(angular,
      InheritApp.TestController2,
      InheritApp.TestService,
      new InheritApp.TestFactory().ctor,
      new InheritApp.TestDirective().ctor);
}

Basically, the Angular parts that need to new() components (Controllers and Services) get the function pointer to the class, while components that depend on the object already being created (Directives and Factories) have a function pointer passed in that returns an object that in turn points to the innards of the class.

So I refactored all my webGL code to FAN and lo, all was good. I made good progress on building my shiny 3D charts.

Well, charts are pretty similar, so I wanted to take advantage of TypeScript’s inheritance, make a BaseChart class, which I would then extend to Area, Bar, Column, Scatter, etc. What I expected to be able to do was take a base method:

public fatArrowFunction = (arg:string):void => {
   alert("It's Parent fatArrowFunction("+arg+")");
};

And extend it:

public fatArrowFunction = (arg:string):void => {
   super.fatArrowFunction(arg)
   alert("It's Child fatArrowFunction("+arg+")");
};

“Um, no.”, said the compiler. “super() cannot be used with FAN”.

“WTF?” Said I.

It turns out that this is a known not-really-a-bug, that people who are combining Angular and TypeScript run into. After casting around for a bit, I found the fix as well:

class Base {
   constructor() {
      for (var p in this) {

         if (!Object.prototype.hasOwnProperty.call(this, p) && typeof this[p] == 'function') {
            var method = this[p];
            this[p] = () => {
               method.apply(this, arguments);
            };
            // (make a prototype method bound to the instance)
         }
      }
   }
}

Basically what this does is scan through the prototype list and set a bunch of fat arrow function pointers that point back to the prototype function. It seems that there are some people that complain, but as a developer who cut his teeth on C programming, I find function pointers kind of comforting. They become a kind of abbreviation of some big complex thing.

The problem is that the example doesn’t’ quite work, at least in the browsers I’m currently using (Chrome 41, IE 11, FF 36). Instead of pointing at their respective prototypes, all the pointers appear to reference the last item of the loop. And the behavior doesn’t show up well in debuggers. I had to print the contents of the function to see that the pointer named one thing was pointing at another. And this happened in a number of contexts. For example, this[fnName] = () => {this[‘__proto__’][fnName].apply(this, arguments);} gives the same problem.

After a few days of flailing and learning a lot, I went back to basics and tried setting the function pointers explicitly in the constructor of each class. It worked, and it wasn’t horrible. Then, and pretty much just for kicks, I added the base class back in with this method:

public setFunctionPointer(self:any, fnName:string):void{
   this[fnName] = function () {
      //console.log("calling ["+fnName+"]")
      return self['__proto__'][fnName].apply(self, arguments);
   };
}

And gave it a shot. And it worked! I was pleasantly surprised. And because I’m an eternal optimist, I added the loop back, but this time using the function call:

constructor() {
   var proto:Object = this["__proto__"];
   var methodName:string;

   for (var p in proto){
         methodName = p;
         if(methodName !== 'constructor'){
            this.setFunctionPointer(this, methodName);
         }
         //console.log("\t"+methodName+" ("+typeof proto[p]+")");
      }
}

And that, my droogs, worked.

I think it’s a prototype chaining issue, but I’m not sure how. In the non-working code, we’re basically setting this[fnName] = function () { this[fnName].apply(self, arguments)}. That should chain up to the prototype and work, but I don’t think it is. Rather, all the functions wind up chaining to the same place.

function Base() {
    var _this = this;
    for (var p in this) {
        if (!Object.prototype.hasOwnProperty.call(this, p) && typeof this[p] == 'function') {
            var method = this[p];
            this[p] = function () {
                method.apply(_this, arguments);
            };
        }
    }
}

On the other hand, look at the code generated when we use the function we get the following:

var ATSBase = (function () {
    function ATSBase() {
        var proto = this["__proto__"];
        var methodName;
        for (var p in proto) {
            methodName = p;
            if (methodName !== 'constructor') {
                this.setFunctionPointer(this, methodName);
            }
        }
    }
    
    ATSBase.prototype.setFunctionPointer = function (self, fnName) {
        this[fnName] = function () {
            //console.log("calling ["+fnName+"]")
            return self['__proto__'][fnName].apply(self, arguments);
        };
    };
    return ATSBase;
})();

Now, rather than starting at the root, the actual call is done in the prototype. I think this may cause the chain to start in the prototype object, but then again, looking at the code, I don’t see why that should be the case. One clear difference is the fact that in the first version, “this” can be in two closure states (this[p] = function (){method.apply(_this, arguments);};). So it could be closure is behaving in less than obvious ways.

Unfortunately, we are at the point in development where something works, so it’s time to move on. Maybe later after the codebase is more mature, I’ll come back and examine this further. You can explore a running version here.

Web Dev Jenga

Back in the distant past, some very smart people wrote a paper about the past, present and future of user interface software tools. In it they discuss the idea of a tool having a low threshold to learning and a high ceiling of capability. Inevitably, they say, we build tools that start with low threshold and slowly add capability until the high ceiling of capability is reached. Unfortunately, this (almost?) always means that the low threshold to learn is lost amid all the added complexity.

I have seen this happen with FORTRAN, C/C++, Java, JavaScript, and HTML. It’s a pain, but I think it’s inevitable. Interestingly, I think that if you keep things hard, they paradoxically stay simple. The difference between GL, OpenGL and WebGL is really not all that different. There was a big change with the introduction of shaders, but that’s one major shift in something like 20 years.

Now it’s happening to tools. It’s easy to write a quick tool that handles some aspect of development. If it has low threshold for learning and good utility, then it gets picked up and suddenly we have a new way of doing the same old thing. Maybe it’s better, but often it’s just different. The unfortunate result is now we have stacks of frameworks, languages and tools that we don’t understand well. The normal scenario is:

  • Have a confounding problem.
  • Ask Google/StackOverflow about it.
  • Try the responses that seem best until something works
  • Move on to the next confounding problem

As a professional developer, I only have so much time to drill down into things to obtain deep understanding. Many times, you have to trust. It’s faith-based coding, and it really reminds me of building a tower from Jenga blocks. We add and subtract things all the time. It’s a miracle that the thing stays up as often as they do.

My adventures with ‘thrangularJS’ has settled down to the point where I’m building reasonably complex pieces that need to be assembled in a particular order. The watcher in IntelliJ will compile TypeScript to JavaScript, but just in the context of that one file. If a change has been made in a TypeScript file, chances are that it will have to ramify through the project. This is one of those things that has to happen using compilers that doesn’t happen with interpreters.

So, I start to look at what the web development community is doing with dependency management these days. The answer seemed to be Grunt with a typescript task. This worked, but it compiled all the files even if only one needed to be changed. What I really wanted was a makefile. But the makefile needed to be triggered by a watcher. It turns out that there has been some thought on this, and it works in a clean way.

Since I’m on a windows box, I’m using GnuMake. It’s extremely stable, last updated in 2006 (when iPhones were introduced, I think). I’m also using Grunt, installed by npm. Not as stable as make, but it’s never done me wrong. Following the install of make, and Grunt the components have to be set up in the project directory:

npm init
npm install grunt --save-dev
npm install grunt-exec --save-dev
npm install grunt-contrib-watch --save-dev

Then we need a makefile. This is mine, and there are probably better ways to do it. But it’s clear (you can learn everything you ever wanted to know about make here):

CC = tsc 
CFLAGS=  --declaration --noImplicitAny --target ES5 --sourcemap

build: modules/AppMain.js

modules/AppMain.js : directives/WGLA2_directives.js controllers/WGLA1_controller.js \
   modules/AppMain.ts
   $(CC) $(CFLAGS) modules/AppMain.ts

classes/WebGlInterfaces.js : classes/WebGlInterfaces.ts
   $(CC) $(CFLAGS) classes/WebGlInterfaces.ts

classes/WebGlCanvasClasses.js : classes/WebGlInterfaces.js \
           classes/WebGlCanvasClasses.ts
   $(CC) $(CFLAGS) classes/WebGlCanvasClasses.ts

classes/WebGlComponentClasses.js : classes/WebGlInterfaces.js  \
   classes/WebGlComponentClasses.ts
   $(CC) $(CFLAGS) classes/WebGlComponentClasses.ts

controllers/WGLA1_controller.js : classes/WebGlInterfaces.js classes/WebGlComponentClasses.js classes/WebGlCanvasClasses.js \
   controllers/WGLA1_controller.ts
   $(CC) $(CFLAGS) controllers/WGLA1_controller.ts

directives/WGLA2_directives.js : classes/WebGlInterfaces.js classes/WebGlComponentClasses.js classes/WebGlCanvasClasses.js \
   directives/WGLA2_directives.ts
   $(CC) $(CFLAGS) directives/WGLA2_directives.ts

Last, we need a GruntFile.js to knit it all together:

module.exports = function (grunt) {
    //grunt.loadNpmTasks('grunt-ts');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-exec');

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        exec: {
            make: {
                command: 'make build'
            }
        },
        watch: {
            files: ['**/*.ts', '!**/*.d.ts'],
            tasks:['exec:make'] //tasks: ['ts']
        }

    });

    grunt.registerTask('default', ['watch']);

}

And that’s it. Make is a little tricky to learn (high threshold), but has tremendous power and flexibility (high ceiling). Grunt is kept simple and obvious and can be swapped out easily if something better comes along. Other tasks can be added to make such as uglify, test, deploy, pretty much whatever you want. And it’s guaranteed to go in the right order.

It’s a good block to keep in your Jenga tower.

Typescript Headers and Browser Quirks.

It’s been a pretty good week. The WebGl graphics in the directive are connected to the user functionality in the controller, I have tooltips running, and even have raycasting working, so the 2D items appear in the overlay plane above the 3D object:

AngularJSWebGl

 

The big problem that I needed to chase down was circular references in the typescript files. TypeScript uses reference path comments to tell the compiler where to look for type and structure information. Below is the information that I need for the angular module that creates the above application

/// <reference path="../../definitelytyped/angularjs/angular.d.ts" />
/// <reference path="../controllers/WGLA1_controller.d.ts" />
/// <reference path="../directives/WGLA2_directives.d.ts" />

In this case note that there is a path for controller and directive code. In this case, pointing directly to the code file is fine, but I have a case where my WebGLCanvas has to know about WebGLComponents and vice versa. The typescript compiler (tsc) doesn’t like that, and barfs a ‘duplicate definition’ error. At this point, I was wondering why TypeScript doesn’t have a #pragma once directive that would prevent this sort of thing, or even an #ifndef capability. It’s a preprocessor after all, and it should be able to do this. Easily.

But TypeScript does have interfaces. So in this case, I put interfaces for both modules in a single file, which I could then refer to in the downstream files and avoid the circular dependency issue.

The other issue was browsers not playing well together. I kind of thought that we had gotten beyond that, but no.

I develop with IntelliJ, and their debugger plays the best with Chrome, so that’s my default browser. At the end of the day, I’ll check to see that everything runs in IE and FF. And today FF was not playing well, and the tooltips I worked so hard on were not showing. WTF, I say.

If you look at the screenshot above, you’ll see the white text at the upper left. That’s my real-time logging (it’s pointless to write to the console at 30hz). And I could see that the unit mouse values were NaN. Again, WTF.

Now FF has my favorite debugger, and it even works (generally) with typescript, as long as you have all the .ts and .map files alongside your .js files. So I stepped into the code at the handleMouseEvents() method in WebGlCanvasClasses and started looking.

I’ve been getting the mouse coordinate from MouseEvent.offsetX. That turns out be used by IE and Chrome, but not FF. so I changed

var sx:number = ev.offsetX; to var sx:number = ev.offsetX | ev.layerX;

All fixed, I thought. But wait! There’s more! It turns out that IE has both of these values, and they don’t mean the same thing. so in the end I wind up with the following monkeypatch:

handleMouseEvents = (ev:MouseEvent):void => {
    var sx = ev.layerX;
    var sy = ev.layerY;

    if(ev.offsetX < sx){
        sx = ev.offsetX;
        sy = ev.offsetY;
    }
}

This works because the smaller value has to be the coordinate of the mouse on the div I’m interested, since all screen coordinates increase from 0. So it’s quick, but jeez.

Text Overlay for ThreeJS with Angular and TypeScript

This is not my first foray into WebGL. The last time I was working on a 3D charting API using the YUI framework, which could do things like this:

Personally, I can’t do any debugging at 30fps without having a live list of debugging text that I can watch. So almost immediately after the ‘hello world’ spinning cube, I set that up. And now I’m in the middle of moving my framework over to Angular and TypeScript. For the most part, I like how things are working out, but when it comes to lining up a transparent text plane over a threeJS element, YUI gives a lot more support than Angular. The following is so brute-force that I feel like I must be doing it wrong (And there may be a jquery-lite pattern, but after trying a few StackOverflow suggestions that didn’t work), I went with the following.

First, this all happens in the directive. I try to keep that pretty clean:

// The webGL directive. Instantiates a webGlBase-derived class for each scope
export class ngWebgl {
   private myDirective:ng.IDirective;

   constructor() {
      this.myDirective = null;
   }

   private linkFn = (scope:any, element:any, attrs:any) => {
      //var rb:WebGLBaseClasses.RootBase = new WebGLBaseClasses.RootBase(scope, element, attrs);
      var rb:WebGlRoot = new WebGlRoot(scope, element, attrs);
      scope.webGlBase = rb;
      var initObj:any = {
         showStage: true
      };
      rb.initializer(initObj);
      rb.animate();
   };

   public ctor = ():ng.IDirective => {
      if (!this.myDirective) {
         this.myDirective = {
            restrict: 'AE',
            scope: {
               'width': '=',
               'height': '=',
            },
            link: this.linkFn
         }
      }
      return this.myDirective;
   }
}

The interface with all the webGL code happens in the linkFn() method. Note that the WebGLRoot class gets assigned to the scope. This allows for multiple canvases.

WebGLRoot is a class that inherits from WebGLBaseClasses.CanvasBase, which is one of the two big classes I’m currently working on. It’s mostly there to make sure that everything inherits correctly and I don’t break that without noticing:-)

Within WebGLBaseClasses.CanvasBase is the initializer() method. That in turn calls the methods that set up the WebGL and the ‘stage’ that I want to interact with. The part we’re interested for our overlay plane is the overlay canvas’ context. You’ll needthat  to draw into later:

overlayContext:CanvasRenderingContext2D;

This is set up along with the renderer. Interesting bits are in bold:

this.renderer = new THREE.WebGLRenderer({antialias: true});
this.renderer.setClearColor(this.blackColor, 1);
this.renderer.setSize(this.contW, this.contH);

// element is provided by the angular directive
this.renderer.domElement.setAttribute("class", "glContainer");
this.myElements[0].appendChild(this.renderer.domElement);

var overlayElement:HTMLCanvasElement = document.createElement("canvas");
overlayElement.setAttribute("class", "overlayContainer");
this.myElements[0].appendChild(overlayElement);
this.overlayContext = this.overlayElement.getContext("2d");

The first thing to notice is that I have to add CSS classes to the elements. These are pretty simple, just setting absolute and Z-index:

.glContainer {
    position: absolute;
    z-index: 0;
}

.overlayContainer {
    position: absolute;
    z-index: 1;
}

That forces everything to have the same upper left corner. And once that problem was solved, drawing is pretty straightforward. The way I have things set up is with an animate method that uses requestAnimationFrame() wich then calls the render() method. That draws the 3D, and then hands the 2D context off to the draw2D() method:

draw2D = (ctx:CanvasRenderingContext2D):void =>{
   var canvas:HTMLCanvasElement = ctx.canvas;
   canvas.width = this.contW;
   canvas.height = this.contH;
   ctx.clearRect(0, 0, canvas.width, canvas.height);
   ctx.font = '12px "Times New Roman"';
   ctx.fillStyle = 'rgba( 255, 255, 255, 1)'; // Set the letter color
   ctx.fillText("Hello, framecount: "+this.frameCount, 10, 20);
};

render = ():void => {
   // do the 3D rendering
   this.camera.lookAt(this.scene.position);
   this.renderer.render(this.scene, this.camera);
   this.frameCount++;

   this.draw2D(this.overlayContext);
};

I’m supplying links to to the running code and directives, but please bear in mind that this is in-process development and not an minimal application for clarity.

Lexical Scoping and a revisit of AngularJS + Typescript

In the process of putting together my first ‘real’ Angular/TypeScript application, I ran into a frustrating problem: the callback functions that I was using in my $http calls were unable to reach other functions (methods?) in my TypeScript objects.

It turned out that it has to do with the way that TypeScript has to deal with the self = this problem. To tell TS (and EcmaScript 6) to use the ‘this’ from the calling function, functions are created using ‘fat arrow’ notation (=>), something that I had seen, but not really paid attention to.

The Mozilla Developer Network discusses fat arrows in JavaScript here. The part about ‘lexical this is worth paraphrasing here:

Until arrow functions, every new function defined its own this value (a new object in case of a constructor, undefined in strict mode function calls, the context object if the function is called as an “object method”, etc.). This proved to be annoying with an object-oriented style of programming. In ECMAScript 3/5, this issue was fixed by assigning the value in this (e.g. self) to a variable that could be closed over. Arrow functions capture the this value of the enclosing context, so the following code works as expected.

function Person(){
  this.age = 0;

  setInterval(() => {
    this.age++; // |this| properly refers to the person object
  }, 1000);
}

var p = new Person();

So TypeScript works the same way, but it has to compile to current JavaScript. I had several areas in my code where I needed access to ‘this’, for example in lambda functions. In TypeScript, the way you keep lexical scoping looks like this:

this.querySpeech.onend = (event:Event) => {
   this.queryService.submit(this.query, this.goodUserQuery, this.errorResponse);
};

And the generated Javascript looks like this:

this.querySpeech.onend = function (event) {
    _this.queryService.submit(_this.query, _this.goodUserQuery, _this.errorResponse);
};

Note that rather than ‘self’ TypesScript has defined ‘_this’. It’s declared as you would expect it – var _this = this;.

With respect to methods, the pattern in similar. Rather than declaring a method in the ‘default manner:

public runQuery(query:string){
   this.query = query;
   this.submit();
};

A ‘scoped’ method should be declared as follows:

public runQuery = (query:string) => {
   this.query = query;
   this.submit();
};

These result in very different JavaScript. The former generates a prototype:

QueryController.prototype.runQuery = function (query) {
    this.query = query;
    this.submit();
};

While the latter generates a function that is within the ‘constructor’:

this.runQuery = function (query) {
    _this.query = query;
    _this.submit();
};

To me, it’s clearer how things will work out with a callback in the second function. Because we’re using _this via closure, we know that we’ll get only members of our class. With the other JavaScript, things are much less obvious– ‘this’ could be global, or what apply() would pass in. Scary.

So now we have TypeScript classes that behave the way that (I think) a proper OO class should behave. Which makes me think about the pattern of using static methods for building Factories and Directives that I described a few posts ago. Maybe there’s a better way.

Factories and directives want a function that returns an object that contains what they need to work with. In the case of a directive, angular is pretty particular, and will need to look something like:

public ctor = (gService:ITestService):ng.IDirective => {
   var myDirective:ng.IDirective = {
      template: '<p>Directive (Ctor) = ' + gService.getHello() + ', linkFn = {{name}}</p>',
      restrict: 'AE',
      link: this.linkFn
   };
   myDirective;
};

Factories, on the other hand pretty much just want references to the functions that will be accessed.

public ctor = () => {
   var retval = {
      getHello: this.getHello
   };
   return retval;
};

The neat thing is that now that the functions have lexical scope, we can instance them and then just pass the reference to the ctor() method to angular, and it’s happy. Below is how I like to initialize my Angular apps. Note that the Factory and Directive classes are instanced with new before being passed in:

module AngularApp {
// define how this application assembles.
   class AngularMain {
      serviceModule:ng.IModule;
      appModule:ng.IModule;

      public doCreate(angular:ng.IAngularStatic, tcontroller:Function, tservice:Function, tfactory:Function, tdirective:Function) {
         this.serviceModule = angular.module('globalsApp', [])
            .factory('GlobalsFactory', [tfactory])
            .service('GlobalsService', [tservice]);

         this.appModule = angular.module('simpleApp', ['globalsApp'])
            .controller('MainCtrl', ['GlobalsFactory', 'GlobalsService', tcontroller])
            .directive('testWidget', ['GlobalsService', tdirective]);
      }
   }
// instantiate Angular with the components defined above.
   new AngularMain().doCreate(angular,
      InheritApp.TestController2,
      InheritApp.TestService,
      new InheritApp.TestFactory().ctor,
      new InheritApp.TestDirective().ctor);
}

So now we have a much cleaner way of dealing with angular components that supports OO patterns and inheritance without having to write parasitic inheritance functions. And we get typing! I am a happy web developer.

The full code that demonstrates all of the above is in the following links:

Hopefully, this is the last of my general purpose struggles with getting Angular and JavaScript to be reasonably well behave OOP objects. Next posts should be about getting this all working with threejs, and maybe a little gpu programming

TypeScript and AngularJS part 2; the Good, the Bad and the Ugly.

As will become clear, this is the takehome message:

  • Directives and Factories, because they are used without new(), must be created as static TypeScript objects.
  • Controllers and Services can be plain old typescript objects (potsos?)

Naturally, there are ramifications.

Let’s start at the end, where everything is combined and delivered to Angular:

module AngularApp {
   // define how this application assembles.
   class AngularMain {
      serviceModule:ng.IModule;
      appModule:ng.IModule;

      public doCreate(angular:ng.IAngularStatic, tcontroller:Function, tservice:Function, tfactory:Function, tdirective:Function) {
         this.serviceModule = angular.module('globalsApp', [])
            .factory('GlobalsFactory', [tfactory])
            .service('GlobalsService', [tservice]);

         this.appModule = angular.module('simpleApp', ['globalsApp'])
            .controller('MainCtrl', ['GlobalsFactory', 'GlobalsService', tcontroller])
            .directive('testWidget', ['GlobalsService', tdirective]);
      }
   }
   // instantiate Angular with the components defined above.
   new AngularMain().doCreate(angular, InheritApp.TestController2, InheritApp.TestService, InheritApp.TestFactory.ctor, InheritApp.TestDirective2.ctor);
}

This structure isn’t needed, but as with the last post, I kind of like the way it looks. The first thing to notice is that the angular-specific code is wrapped in its own module and class within that module. Since this isn’t going to get called outside of the module (this would be custom for each application), I didn’t bother with an interface. Once the class is built, I call it with the arguments that will be used by Angular to build the application. There are two things to note: the arguments with the ctor member are static. The items with a ‘2’ in their names are child classes, built with typescript-defined inheritance.

Let’s take a look at the controller and the service that gets passed in.

Controllers and Services, since they are instances, require virtually no contortions to use. A controller is declared pretty much just the way you’d want to. (I have the classes for this example wrapped in a module that I can then export from – full code here) . The following controller has an interface, a class that implements that interface, and a constructor that takes angular injections.

export interface ITestController {
   myString:string;
   serviceString:string;
   factoryString:string;
}
export class TestController implements ITestController {
   myString:string;
   serviceString:string;
   factoryString:string;

   constructor(gFactory:ITestService, gService:ITestService) {
      this.myString = "Hello, TypeScript4";
      this.serviceString = gService.getHello();
      this.factoryString = gFactory.getHello();
   }
}

The child class is built as follows. I added a new variable, and modified a parent variable in the constructor::

// example on an inherited interface and controller
export interface ITestController2 extends ITestController {
   myInheritedString: string;
}
// the associated controller.
export class TestController2 extends TestController implements ITestController2 {
   myInheritedString:string;

   constructor(gFactory:ITestService, gService:ITestService) {
      super(gFactory, gService);
      this.myInheritedString = "Hello, inheritance";
      this.myString += " from your child"
   }
}

In case you were wondering (you can look at the generated code here), typescript uses parasitic inheritance.

The service in this example is constructed essentially identically to the controller:

// example service with interface
export interface ITestService {
   helloStr:string;
   getHello():string;
}
export class TestService implements ITestService {
   helloStr:string;

   constructor() {
      this.helloStr = "TestService String";
   }

   public getHello():string {
      return "Hello from TestService";
   }
}

Now let’s compare the service to a factory. Factories are set up by angular to be singletons, while services can breed like bacteria and clog all your memory. Typescript uses a static** property to define singletons, so a factory in typescript looks like this:

// Factory. Like the directive, factories are called without new, 
// so no this, and all references to the factory are references 
// to the same object. 
export class TestFactory {
   static helloStr:string = "TestFactory String";

   public static ctor() {
      var retval = {
         getHello: TestFactory.getHello
      };
      return retval;
   }

   public static getHello():string {
      return TestFactory.helloStr;
   }
}

This is a little more clunky, but it does make what’s going on clearer, at least for me. Note how you can’t have any items attached to the ‘this’ object. They have to be explicitly attached to the ‘class definition’. As such the static/singleton status is hard to overlook.

Inheritance will work on static classes, but with some odd considerations. This is the parent and child directives:

// directives have to be static, as they are called without the 
// 'new' operator, which means they have no 'this' They also 
// don't get interfaces, since all the functions are static 

export class TestDirective implements ng.IDirective {

   public static  linkFn(scope:any, element:any, attr:ng.IAttributes) {
      function sayIt(str:string):string{
         return str;
      }
      scope.name = "Hello from linkFn";
      scope.sayIt = sayIt;
      alert (sayIt("alert me!"));
   }

   public static ctor(gService:ITestService):ng.IDirective {

      var directive:ng.IDirective = {};
      directive.template = '<p>Directive (Ctor) = ' + gService.getHello() + ', linkFn = {{name}}</p>';
      directive.restrict = 'AE';
      directive.link = TestDirective.linkFn; // silly, but necessary.
      return directive;
   }
}

export class TestDirective2 extends TestDirective {
   public static ctor(gService:ITestService):ng.IDirective {

      var directive:ng.IDirective = {};
      directive.template = '<p>Inherited Directive (Ctor) = ' + gService.getHello() + ', linkFn = {{name}}</p>';
      directive.restrict = 'AE';
      directive.link = TestDirective2.linkFn; // silly, but necessary.
      return directive;
   }
}

There are a couple of things to note in the code above. First, the directive as it is built in the ctor() method is created as an empty object and then populated. This is how I found it being done in examples on the web, and I believe it helps determine typing. I’m not convinced though – I’ll have to check by putting something mis-typed inside the object definition. By the way, note that services or factories can be passed to the directive as arguments to the ctor() method.

The second odd thing is the directive.link function. I would have thought that this could have been done a variety of ways, but this is how Angular likes it. And because everything is static, I wound up using functions inside the linkFn class since you can’t nest typescript-style methods in a clear way.

With respect to inheritance, directives are going to be a pain.  You can’t easily overload parts of the parent class to add capability to the child class. It may actually be easier to use inheritance on just the link function. I’m still not sure what the best way to go on that is. It will probably only become clear when I try to write some sophisticated directives (and, boy do I have one to work on…).

So there is good, not-so-bad and ugly. I’d be curious if anyone has a better pattern, particularly for directives.

—————————-

** It turns out that there is a non-static way to treat directives and factories, which is instancing them and then passing a function reference to angular. I think this works much better. For more detail, check out this post.

OOooo… TypeScript Classes with AngularJS

Let’s add TypeScript to the mix. I like typing – basically because I hate making unforced errors. I like interfaces for the same reason – they allow defining complex types before they get used.

I’ve known about TypeScript for a while, but I wasn’t good enough with JavaScript to really understand what it was doing. It just didn’t seem like a good idea to add yet another abstraction to the already shaky tower of JavaScript, Angular and threeJS.

But now I’ve been working with some reasonably complex JavaScript and have enough comprehension to understand the conversions that TypeScript makes. I might even be consciously competent:

TypeScript has been used with Angular before, and it’s also part of the plan for Angular 2.0. Sean Hess has a nice angular with typescript video. The key points are really around 15:00 in, where the controllers and factories are built. His github repository for the demo code is here. It was great to see that TypeScript and Angular can be combined, but I really wanted something as simple as possible, so I got a copy of TypeScript Essentials and started with the basics.

With that in mind, I’ve tried to make a very simple TypeScript class and incorporate it into the angular framework using a second TypeScript class. In the interest of maximum simplicity, there are only classes and typing – no interfaces (other than the ones from definitely typed) and no modules. No inheritance either. All these will be in a later post.

So, without any more introduction, here are the results:

  • First, plain old angular HTML:
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body ng-app="simpleApp">
<div ng-controller="MainCtrl as mc">
    <p>String = {{mc.myString}}</p>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>
<script src="simple.js"></script>

</body>
</html>
  • Next, the TypeScript (simple.ts):
/// <reference path="../definitelytyped/angularjs/angular.d.ts" />

class TestClass{
   myString:string;

   constructor(){
      this.myString = "Hello, TypeScript4";
   }
}

class AngularMain{
   myModule:ng.IModule;
   myController:ng.IModule;
   public doCreate(angular:ng.IAngularStatic, sfn:Function){
      this.myModule = angular.module('simpleApp', []);
      this.myController = this.myModule.controller('MainCtrl', [sfn]);
   }
}

new AngularMain().doCreate(angular, TestClass);
  • Last, the generated JavaScript code (simple.js):
/// <reference path="../definitelytyped/angularjs/angular.d.ts" />
var TestClass = (function () {
    function TestClass() {
        this.myString = "Hello, TypeScript4";
    }
    return TestClass;
})();
var AngularMain = (function () {
    function AngularMain() {
    }
    AngularMain.prototype.doCreate = function (angular, sfn) {
        this.myModule = angular.module('simpleApp', []);
        this.myController = this.myModule.controller('MainCtrl', [sfn]);
    };
    return AngularMain;
})();
new AngularMain().doCreate(angular, TestClass);
//# sourceMappingURL=simple.js.map

I’ve put a running example up here.

Happy coding!

OO inheritance for AngularJS factories

AngularJS  services and factories require a return object. As such, the parasitic combination inheritance calls mentioned in the previous post need to be changed a bit so that the return object from the call to the parent class is stored so that it can be returned from the child class in a way that Angular likes. Here’s what it looks like when using my ‘utility’ inheritance tools:

function QueryServiceFn2($http){
   var retObj = QueryServiceFn.call(this, $http);
   globalU.inheritPrototype(this, QueryServiceFn);
   return retObj;
}

So that works just fine. Closure also works the way that I think it should – methods referenced in the parent class have visibility to the ‘hidden’ parent objects. Here’s full example of inheriting a factory object (full version here – the child class is at the bottom of the file):

globalUtils.appMap.phpFactories2 = (function(globalU, base){
   "use strict";
   function QueryServiceFn($http){
      var retObj = base.call(this, $http);
      globalU.inheritPrototype(this, base);
      return retObj;
   }

   return{
      queryServicePtr: QueryServiceFn
   };
})(globalUtils, globalUtils.appMap.phpFactories.queryServicePtr);

To override a function, simply declare it normally and then set the pointer in retObj to point at the new version. The only thing to watch out for is that closure won’t hold. If you need access to an item in the base class that’s accessed through closure, you’ll probably have to copy it.