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

Commit a4ec297

Browse files
scardinepetebacondarwin
authored andcommitted
fix(scope): watches can be safely unregistered inside watch handlers
Closes #2915
1 parent 93d7e60 commit a4ec297

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
@@ -393,7 +393,7 @@ function $RootScopeProvider(){
393393
watch = watchers[length];
394394
// Most common watches are on primitives, in which case we can short
395395
// circuit it with === operator, only when === fails do we use .equals
396-
if ((value = watch.get(current)) !== (last = watch.last) &&
396+
if (watch && (value = watch.get(current)) !== (last = watch.last) &&
397397
!(watch.eq
398398
? equals(value, last)
399399
: (typeof value == 'number' && typeof last == 'number'

test/ng/rootScopeSpec.js

+24
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,30 @@ describe('Scope', function() {
318318
expect(listener).not.toHaveBeenCalled();
319319
}));
320320

321+
it('should allow a watch to be unregistered while in a digest', inject(function($rootScope) {
322+
var remove1, remove2;
323+
$rootScope.$watch('remove', function() {
324+
remove1();
325+
remove2();
326+
});
327+
remove1 = $rootScope.$watch('thing', function() {});
328+
remove2 = $rootScope.$watch('thing', function() {});
329+
expect(function() {
330+
$rootScope.$apply('remove = true');
331+
}).not.toThrow();
332+
}));
333+
334+
it('should allow a watch to be added while in a digest', inject(function($rootScope) {
335+
var watch1 = jasmine.createSpy('watch1'),
336+
watch2 = jasmine.createSpy('watch2');
337+
$rootScope.$watch('foo', function() {
338+
$rootScope.$watch('foo', watch1);
339+
$rootScope.$watch('foo', watch2);
340+
});
341+
$rootScope.$apply('foo = true');
342+
expect(watch1).toHaveBeenCalled();
343+
expect(watch2).toHaveBeenCalled();
344+
}));
321345

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

0 commit comments

Comments
 (0)