Thursday, April 14, 2016

Refusing deeply nested code

I have this angular directive, and I don't want nested code, so I don't embed the function directly in the link property:

angular.module("AcroformBuilder", [])
    .directive('afBuilder', [() => {
            return <ng.IDirective>{
                restrict: 'E',
                scope: {
                    metaDataGetter: '&',
                    savedDataGetter: '&',
                    afObject: '='
                },
                link: FormBuilder
            };

        }]);

.
.
.
function FormBuilder(scope: IScopeProperties, element: ng.IRootElementService, attrs: ng.IAttributes) {





Eventually, I needed the $q service. Since the link property cannot be dependency injected, the easiest way to solve the problem is to move the function directly to link property. However did I say I refuse deeply nested code? And if you can infer from the code above, directly embedding the function in the directive's link would make the function deeply nested, around 16 spaces or 4 tabs from the left.



To cut to the chase, javascript has this magical function to pass invisible parameter whenever a function is called. That magical function is called bind.

Just bind two parameters, first the object and then the parameter itself. The link's function is called and not instantiated (javascript functions are like a class, can be instantiated too), so we just pass undefined on first parameter and then pass the $q service on the second parameter.

angular.module("AcroformBuilder", [])
    .directive('afBuilder', ['$q',($q: ng.IQService) => {
            return <ng.IDirective>{
                restrict: 'E',
                scope: {
                    metaDataGetter: '&',
                    savedDataGetter: '&',
                    afObject: '='
                },
                link: FormBuilder.bind(undefined, $q)
            };

        }]);

.
.
.
function FormBuilder($q: ng.IQService, scope: IScopeProperties, element: ng.IRootElementService, attrs: ng.IAttributes) {




Happy Coding!

No comments:

Post a Comment