Created
July 19, 2013 17:19
-
-
Save ProLoser/6040838 to your computer and use it in GitHub Desktop.
AngularJS: When to use $scope.$apply()?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*** BAD: *** | |
* Never put $scope.$apply() deep down a call stack | |
* You may end up calling the same method inside a | |
* $digest, and find yourself using $scope.$$phase | |
* or $timeout to hack around it. | |
*/ | |
setTimeout(function(){ | |
a(); | |
}) | |
elm.bind('click', function(){ | |
a(); | |
}) | |
socket.onmessage = function(){ | |
a(); | |
} | |
a = function() { | |
b(); | |
} | |
b = function() { | |
c(); | |
} | |
c = function() { | |
// do very specific logic | |
$scope.foo = bar; | |
// etc | |
$scope.$apply(); | |
} | |
/*** GOOD: *** | |
* Always put $scope.$apply() at the TOP of your call stack | |
* make sure $apply() is as close to the async binding as possible | |
*/ | |
setTimeout(function(){ | |
$scope.$apply(function(){ | |
a(); | |
}); | |
}) | |
elm.bind('click', function(){ | |
$scope.$apply(function(){ | |
a(); | |
}); | |
}) | |
socket.onmessage = function(){ | |
$scope.$apply(function(){ | |
a(); | |
}); | |
} | |
a = function() { | |
b(); | |
} | |
b = function() { | |
c(); | |
} | |
c = function() { | |
// do very specific logic | |
$scope.foo = bar; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment