Invoking function breaks scope

2019-09-09 22:23发布

Same issue as here: AngularJS directive binding a function with multiple arguments

Following this answer: https://stackoverflow.com/a/26244600/2892106

In as small of a nutshell as I can.

This works:

<my-directive on-save="ctrl.saveFn"></my-directive>

With:

angular.module('app')
.controller('MyController', function($scope) {
  var vm = this;
  vm.saveFn = function(value) { vm.doSomethingWithValue(value); }
});

But when I convert to Typescript and use real classes, this breaks.

class MyController {
  constructor() {}

  saveFn(value) {
    this.doSomethingWithValue(value);
  }
}

In the Typescript version when debugging, "this" is referencing the Window global. So my scope is messed up somehow, but I don't know how to fix it. How can I get "this" to refer to MyController as expected?

1条回答
戒情不戒烟
2楼-- · 2019-09-09 22:30

So my scope is messed up somehow

Use an arrow function instead of a method.

Fixed

class MyController {
  constructor() {}

  saveFn = (value) => {
    this.doSomethingWithValue(value);
  }
}

More

https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

查看更多
登录 后发表回答