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

Commit 6b138db

Browse files
committed
fix($rootScope): avoid unstable reference in $broadcast event
The event.currentScope was a reference to the iterator of the scope traversal (`current`). It caused problems when accessing the event.currentScope asynchronously : it was the last scope of the traversal instead of the scope which listen the event.
1 parent 3f540e3 commit 6b138db

File tree

2 files changed

+15
-10
lines changed

2 files changed

+15
-10
lines changed

src/ng/rootScope.js

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1096,23 +1096,25 @@ function $RootScopeProvider(){
10961096
* @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
10971097
*/
10981098
$broadcast: function(name, args) {
1099+
function Event(currentScope) {
1100+
this.name = name;
1101+
this.currentScope = currentScope;
1102+
this.targetScope = target;
1103+
this.defaultPrevented = false;
1104+
}
1105+
Event.prototype.preventDefault = function() {
1106+
this.defaultPrevented = true;
1107+
}
1108+
10991109
var target = this,
11001110
current = target,
11011111
next = target,
1102-
event = {
1103-
name: name,
1104-
targetScope: target,
1105-
preventDefault: function() {
1106-
event.defaultPrevented = true;
1107-
},
1108-
defaultPrevented: false
1109-
},
1110-
listenerArgs = concat([event], arguments, 1),
1112+
listenerArgs,
1113+
event = new Event(current),
11111114
listeners, i, length;
11121115

11131116
//down while you can, then up and next sibling or up and next sibling until back at root
11141117
while ((current = next)) {
1115-
event.currentScope = current;
11161118
listeners = current.$$listeners[name] || [];
11171119
for (i=0, length = listeners.length; i<length; i++) {
11181120
// if listeners were deregistered, defragment the array
@@ -1124,6 +1126,8 @@ function $RootScopeProvider(){
11241126
}
11251127

11261128
try {
1129+
event = new Event(current);
1130+
listenerArgs = concat([event], arguments, 1);
11271131
listeners[i].apply(null, listenerArgs);
11281132
} catch(e) {
11291133
$exceptionHandler(e);

test/ng/rootScopeSpec.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1700,6 +1700,7 @@ describe('Scope', function() {
17001700
it('should receive event object', inject(function($rootScope) {
17011701
var scope = $rootScope,
17021702
child = scope.$new(),
1703+
grandChild = child.$new(),
17031704
event;
17041705

17051706
child.$on('fooEvent', function(e) {

0 commit comments

Comments
 (0)