Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does `$scope.$apply() isn't high enough in the call stack` mean in this anti-pattern

I'm reading through this document which presents anti-patterns and there is the following there: Don't do if (!$scope.$$phase) $scope.$apply(), it means your $scope.$apply() isn't high enough in the call stack. Can anyone please explain me what that means?

I'm specifically interested in the isn't high enough in the call stack part. I know what $$phase and $apply is and why it is used. It would be great to see an example of scope being not high enough in stack.

like image 380
Max Koretskyi Avatar asked Nov 10 '22 01:11

Max Koretskyi


1 Answers

The call stack is the chain of calls made by a certain function, like what you can see inside the console when ther's a javascript error. For example

  at Scope.$scope.openRightMenu (site/header.ctr.js:19:12)
        at Parser.functionCall (site/bower_components/angular/angular.js:10567:21)
        at site/bower_components/angular-touch/angular-touch.js:438:9
        at Scope.$get.Scope.$eval (site/bower_components/angular/angular.js:12412:28)
        at Scope.$get.Scope.$apply (site/bower_components/angular/angular.js:12510:23)
        at HTMLDivElement.<anonymous> (site/bower_components/angular-touch/angular-touch.js:437:13)

This is a call stack. Now the $apply() func must be called when the entire function cycle is finished, that's why it says that it should be in the highest level of the call stack. Because you have to be sure that every process is done in order to make a safe $apply() also because, as you know, you cannot make 2 digest cycles on the same $scope at once.

So if you have

func a() -> calling -> func b() //setting $scope elaborated data
func b() -> calling -> func c() //elaborating data
func c() -> calling -> func d() //getting data

Your $apply() call should be inside func a(), being that the highest level of your call stack.

like image 55
Bolza Avatar answered Nov 14 '22 22:11

Bolza