我正在尝试创建一个实用程序方法,它将附加到 AngularJS 的 $scope$
的 $destroy
事件,以便它自动清理处理程序并避免内存泄漏。下面是这个名为 attachEventToRootscopeAndRegisterUnbind()
的实用方法的一些示例代码,采用 TypeScript,但应该与 JavaScript 非常相似。
class EventToUnRegister {
public $scope: ng.IScope;
public unbindHandler: Function;
public eventName: string;
public logger: Core.ILog;
public onScopeDestroy() {
this.logger.debug("EventToUnRegister:onScopeDestroy",`Scope destroyed, unbinding event '${this.eventName}'`);
this.unbindHandler();
//remove references
this.logger = null;
this.unbindHandler = null;
this.$scope = null;
this.eventName = null;
}
}
attachEventToRootscopeAndRegisterUnbind($scope: ng.IScope, eventName: string, listener: (event: angular.IAngularEvent, ...args: any[]) => any) {
var eventToUnRegister = new EventToUnRegister();
eventToUnRegister.$scope = $scope;
eventToUnRegister.logger = this.logger;
eventToUnRegister.unbindHandler = this.$rootScope.$on(eventName, listener);
eventToUnRegister.eventName = eventName;
$scope.$on("$destroy", () => {
eventToUnRegister.onScopeDestroy(); //<-- IS IT AN ISSUE TO ACCESS THIS HERE?
eventToUnRegister = null; //remove reference to make sure it is cleaned up
});
}
我的问题是:
- 从
$scope.$on
事件处理程序访问eventToUnRegister
是否存在任何问题? - 这样还会出现任何形式的内存泄漏吗?
最初的问题是,您出于任何原因从 Controller 附加到 $rootscope
上的事件。理想情况下,不这样做,但有时需要这样做。然后,由于 $rootscope
永远不会被销毁, Controller 将因该事件而永远存在。我正在尝试创建这个实用方法来解决这个问题。
最佳答案
对我来说看起来完全有效,只要 $destroy
中没有触发相关事件链,我就没有看到任何问题。此外,您不需要如此明确地取消所有内容。如果对包含对象的引用超出范围(并且它的所有子属性都没有以某种方式返回引用),则该对象将被垃圾收集。
关于javascript - 在事件调用中访问函数内部范围之外的对象,以及对象何时被清理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34612355/