我正在通过设置回调函数从 Angularjs 注册“$routeChangeSuccessEvent”。引发事件时,我无法通过“this”访问我的 Controller 实例。当前这个实例是未定义的。
我完整的 TypeScript 代码:
export class Ctlr {
static $inject = ["$rootScope","$route"];
constructor(private $scope: ng.IRootScopeService) {
this.Scope = $scope;
this.Title = "";
//this.Scope.$on("$routeChangeSuccessEvent", this.onRouteChangeStart);
this.RegisterEvents();
}
private RegisterEvents(): void {
this.Scope.$on("$routeChangeSuccessEvent",(event: ng.IAngularEvent, args: any) => {
//this is undefined
console.log(this);
});
}
public Scope: ng.IScope;
public Title: string;
public onRouteChangeStart(event: ng.IAngularEvent, args: any) {
//this is undefined
this.Title = args.$$route.name);
}
}
}
我可以通过以下方式访问 Title 属性:
private RegisterEvents(): void {
var ref = this.Title;
this.Scope.$on("$routeChangeSuccessEvent",(event: ng.IAngularEvent, args: any) => {
ref = args.$$route.name;
});
}
但这不是真正的解决方案,因为 angularJS 不会更新它的 View 。看来我没有捕获正确的引用。如果那不可能,那么整个 angularjs 事件似乎都不是 useabel - 那不可能吗?
我也没有找到任何关于这种奇怪行为的话题。这个问题有解决方案吗?
最佳答案
触发回调时范围会发生变化,这就是 this
变为未定义的原因。
你的另一个例子:
var ref = this.Title;
实际上只是创建了一个 Title
的副本,因为它是原始类型(字符串)。这就是为什么它也不起作用的原因。更新 ref
不会更新 this.Title
。
通常的解决方案是开始定义:
var vm = this;
...
private RegisterEvents(): void {
this.Scope.$on("$routeChangeSuccessEvent",(event: ng.IAngularEvent, args: any) => {
//this is undefined
console.log(vm);
});
}
因此,与其在任何地方都使用 this
,不如使用 vm
。请注意,vm
可以随意命名。重要的部分是您在 this
是您想要在回调中使用的范围内捕获对 this
的引用。这是可行的,因为 this
不是原始类型,因为它是一个对象,它不是获取副本,而是获取引用。
您的另一个选择是使用 bind
,您可以将其应用于任何函数,该函数实质上告诉 JavaScript this
将等同于什么。例如
$scope.$on("SomeEventHere", someCallbackFunction.bind(this));
这是您在这里使用的偏好问题,但通常我看到人们使用 var something = this;
方法。
关于javascript - 在 $scope.$on 事件中丢失此引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31054545/