0

I have several Directives which are very similar in some regard, but very different in others. To reduce the amount of duplicate code inheritance can be used, however I have not yet figured out how to instantiate a directive Class.

Here is what I have tryed:

/// <reference path='../_all.ts' />

module app.directives {
  'use strict';

  export class myDirective implements ng.IDirective
  {

    private margin = {top: 70, right: 20, bottom: 40, left: 55};
    private padding = {top: 10, right: 10, bottom: 10, left: 10};

    public restrict = 'A';
    public $scope = {
      regulationdata: "=",
      title: "="
    };

    constructor(private $window) {}

    public link($scope, element: JQuery, attr: ng.IAttributes)
    {

      // Browser onresize event
      this.$window.onresize = function () {  // TypeError: Cannot read property '$window' of undefined
        $scope.$apply();
      };

      // lots of application specific code.
    }
  }
  /** Register directive */
  angular.module('app').directive('myDirective',['$window', ($window) => { return new myDirective($window); } );


}

The error I receive is: TypeError: Cannot read property '$window' of undefined

1 Answer 1

2

I think this could be a problem with the scope of variables within javasript.Take a look at this answer. This contains the answer described below and has a very nice explanation.

The problem is, that the this pointer in the method link is not set as expected. Just try to implement the link function as lambda function, so typescript take care of setting the this pointer correctly.

Just compare the following results:

export class Test {
    private property: string;
    public link() {
        this.property;
    }
}

export class Test2 {
    private property: string;
    public link = () => {
        this.property;
    }
}
define(["require", "exports"], function(require, exports) {
    var Test = (function () {
        function Test() {
        }
        Test.prototype.link = function () {
            this.property;
        };
        return Test;
    })();
    exports.Test = Test;

    var Test2 = (function () {
        function Test2() {
            var _this = this;
            this.link = function () {
                _this.property;
            };
        }
        return Test2;
    })();
    exports.Test2 = Test2;
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, the video from the link, you added, is really good to explain the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.