Skip to content

Commit d1aac5d

Browse files
scardinectrahey
authored andcommitted
fix(scope): watches can be safely unregistered inside watch handlers
Closes angular#2915
1 parent 6a43c67 commit d1aac5d

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

src/ng/rootScope.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -521,7 +521,7 @@ function $RootScopeProvider(){
521521
watch = watchers[length];
522522
// Most common watches are on primitives, in which case we can short
523523
// circuit it with === operator, only when === fails do we use .equals
524-
if ((value = watch.get(current)) !== (last = watch.last) &&
524+
if (watch && (value = watch.get(current)) !== (last = watch.last) &&
525525
!(watch.eq
526526
? equals(value, last)
527527
: (typeof value == 'number' && typeof last == 'number'

test/ng/rootScopeSpec.js

+24
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,30 @@ describe('Scope', function() {
330330
expect(listener).not.toHaveBeenCalled();
331331
}));
332332

333+
it('should allow a watch to be unregistered while in a digest', inject(function($rootScope) {
334+
var remove1, remove2;
335+
$rootScope.$watch('remove', function() {
336+
remove1();
337+
remove2();
338+
});
339+
remove1 = $rootScope.$watch('thing', function() {});
340+
remove2 = $rootScope.$watch('thing', function() {});
341+
expect(function() {
342+
$rootScope.$apply('remove = true');
343+
}).not.toThrow();
344+
}));
345+
346+
it('should allow a watch to be added while in a digest', inject(function($rootScope) {
347+
var watch1 = jasmine.createSpy('watch1'),
348+
watch2 = jasmine.createSpy('watch2');
349+
$rootScope.$watch('foo', function() {
350+
$rootScope.$watch('foo', watch1);
351+
$rootScope.$watch('foo', watch2);
352+
});
353+
$rootScope.$apply('foo = true');
354+
expect(watch1).toHaveBeenCalled();
355+
expect(watch2).toHaveBeenCalled();
356+
}));
333357

334358
it('should not infinitely digest when current value is NaN', inject(function($rootScope) {
335359
$rootScope.$watch(function() { return NaN;});

0 commit comments

Comments
 (0)