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

Commit

Permalink
fix(scope): watches can be safely unregistered inside watch handlers
Browse files Browse the repository at this point in the history
Closes #2915
  • Loading branch information
scardine authored and petebacondarwin committed Jul 11, 2013
1 parent 4e96334 commit 8bd6619
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/ng/rootScope.js
Original file line number Diff line number Diff line change
Expand Up @@ -521,7 +521,7 @@ function $RootScopeProvider(){
watch = watchers[length];
// Most common watches are on primitives, in which case we can short
// circuit it with === operator, only when === fails do we use .equals
if ((value = watch.get(current)) !== (last = watch.last) &&
if (watch && (value = watch.get(current)) !== (last = watch.last) &&
!(watch.eq
? equals(value, last)
: (typeof value == 'number' && typeof last == 'number'
Expand Down
24 changes: 24 additions & 0 deletions test/ng/rootScopeSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,30 @@ describe('Scope', function() {
expect(listener).not.toHaveBeenCalled();
}));

it('should allow a watch to be unregistered while in a digest', inject(function($rootScope) {
var remove1, remove2;
$rootScope.$watch('remove', function() {
remove1();
remove2();
});
remove1 = $rootScope.$watch('thing', function() {});
remove2 = $rootScope.$watch('thing', function() {});
expect(function() {
$rootScope.$apply('remove = true');
}).not.toThrow();
}));

it('should allow a watch to be added while in a digest', inject(function($rootScope) {
var watch1 = jasmine.createSpy('watch1'),
watch2 = jasmine.createSpy('watch2');
$rootScope.$watch('foo', function() {
$rootScope.$watch('foo', watch1);
$rootScope.$watch('foo', watch2);
});
$rootScope.$apply('foo = true');
expect(watch1).toHaveBeenCalled();
expect(watch2).toHaveBeenCalled();
}));

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

0 comments on commit 8bd6619

Please sign in to comment.