2

The situation: I recently started using Typescript and am currently integrating it into my AngularJS web application. I have been using the 'controller as' syntax instead of $scope where possible.

The issue: I can't seem to find a proper way to replace var self = this; I started replacing vm with this everywhere which soon got me to a dead-end when inside of forEach functions, click events etc.

My temporary solution: casting var self = this; in each function, since I can't cast it globally as far as I understand. It also doesn't work in all cases.

My question: have I missed something obvious? Is there a better way to access the controller's scope?

0

1 Answer 1

5

Fat Arrow functions to the rescue!!!

There is really no need to use var self = this in TypeScript...

Fat arrow functions preserve the (lexical) scope (meaning of this) inside of callback functions:

var self = this;
fooService.doSomething()
  .then(result => {
    console.assert(this === self);  // this is valid and true
  });

For your specific example:

items.forEach((item) => {
  this.somethingElse = item; // (no need for self)
});

Note This is not really a feature of TypeScript, but more so a function of ES6/ES2015

Further Explanation

Sign up to request clarification or add additional context in comments.

1 Comment

So this is what those fat arrows do... it was something obvious after all. Thanks a bunch!

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.