Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

fix($rootScope): cleanup on $destroy also for $rootScope #7564

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions src/ng/rootScope.js
Original file line number Diff line number Diff line change
Expand Up @@ -778,20 +778,21 @@ function $RootScopeProvider(){
* clean up DOM bindings before an element is removed from the DOM.
*/
$destroy: function() {
// we can't destroy the root scope or a scope that has been already destroyed
// we can't destroy a scope that has been already destroyed
if (this.$$destroyed) return;
var parent = this.$parent;

this.$broadcast('$destroy');
this.$$destroyed = true;
if (this === $rootScope) return;

forEach(this.$$listenerCount, bind(null, decrementListenerCount, this));

// sever all the references to parent scopes (after this cleanup, the current scope should
// not be retained by any of our references and should be eligible for garbage collection)
if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
if (parent) {
if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
}
if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;

Expand Down
20 changes: 18 additions & 2 deletions test/ng/rootScopeSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -867,16 +867,32 @@ describe('Scope', function() {
}));


it('should broadcast $destroy on rootScope', inject(function($rootScope) {
it('should allow $destroy of rootScope', inject(function($rootScope) {
var spy = spyOn(angular, 'noop');
$rootScope.$on('$destroy', angular.noop);
$rootScope.$destroy();
$rootScope.$digest();
expect(log).toEqual('123');
expect(log).toEqual('');
expect(spy).toHaveBeenCalled();
expect($rootScope.$$destroyed).toBe(true);
}));

it('should remove all listeners after $destroy of rootScope', inject(function($rootScope) {
var spy = jasmine.createSpy('dummy');
$rootScope.$on('dummy', spy);
$rootScope.$destroy();
$rootScope.$broadcast('dummy');
expect(spy).not.toHaveBeenCalled();
}));

it('should remove all watchers after $destroy of rootScope', inject(function($rootScope) {
var spy = jasmine.createSpy('dummy');
var digest = $rootScope.$digest;
$rootScope.$watch(spy);
$rootScope.$destroy();
digest.call($rootScope);
expect(spy).not.toHaveBeenCalled();
}));

it('should remove first', inject(function($rootScope) {
first.$destroy();
Expand Down