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

refactor($rootScope): add warnings when emitting/broadcasting on a destroyed scope #6784

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
14 changes: 12 additions & 2 deletions src/ng/rootScope.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,8 @@ function $RootScopeProvider(){
return TTL;
};

this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
function( $injector, $exceptionHandler, $parse, $browser) {
this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser', '$log',
function( $injector, $exceptionHandler, $parse, $browser, $log) {

/**
* @ngdoc type
Expand Down Expand Up @@ -970,6 +970,11 @@ function $RootScopeProvider(){
listenerArgs = concat([event], arguments, 1),
i, length;

if (this.$$destroyed) {
$log.warn("Trying to emit '" + name + "' on a destroyed scope");
return event;
}

do {
namedListeners = scope.$$listeners[name] || empty;
event.currentScope = scope;
Expand Down Expand Up @@ -1035,6 +1040,11 @@ function $RootScopeProvider(){
listenerArgs = concat([event], arguments, 1),
listeners, i, length;

if (this.$$destroyed) {
$log.warn("Trying to broadcast '" + name + "' on a destroyed scope");
return event;
}

//down while you can, then up and next sibling or up and next sibling until back at root
while ((current = next)) {
event.currentScope = current;
Expand Down
37 changes: 37 additions & 0 deletions test/ng/rootScopeSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -874,6 +874,43 @@ describe('Scope', function() {
$rootScope.$broadcast(EVENT);
expect(spy.callCount).toBe(1);
}));


it('should warn when emitting on a destroyed scope', inject(function($rootScope, $log) {
var EVENTNAME = 'barEvent',
child = $rootScope.$new(),
warning,
event;

child.$destroy();

expect($log.warn.logs).toEqual([]);
event = child.$emit(EVENTNAME);
expect(event.name).toEqual(EVENTNAME);

warning = $log.warn.logs.shift();

expect(warning[0]).toContain(EVENTNAME);
expect(warning[0]).toContain('emit');
}));


it('should warn when broadcasting on a destroyed scope', inject(function($rootScope, $log) {
var EVENTNAME = 'bazEvent',
warning,
event;

$rootScope.$destroy();

expect($log.warn.logs).toEqual([]);
event = $rootScope.$broadcast(EVENTNAME);
expect(event.name).toEqual(EVENTNAME);

warning = $log.warn.logs.shift();

expect(warning[0]).toContain(EVENTNAME);
expect(warning[0]).toContain('broadcast');
}));
});


Expand Down