Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

angularjs - What is 'cheaper' performance-wise $broadcast or $watch

I have a situation in my application where I need to reload the menu each time the role of the user changes(One user can have roles in several companies).

I was wondering what is the best way to approach this issue.

currently I am doing the following:

app.controller('menuLoadingCtrl', function($location, $scope, authService){
    $scope.model.initialRole = authService.getRole();
    $scope.$watch(function(){return authService.getRole()}, function(val){
        if(val && val != $scope.model.initialRole){
                $scope.layout.menuSrc = 'partials/menu.html';
        }
    });
})

Simple redirecting the user to the menu loading view, and from there, back to the menu view once the role is done loading. I have this wrapped in a function:

 $scope.layout.reloadMenu = function(){
        $scope.layout.menuSrc = 'partials/menuLoading.html';
    }

which I call at any scenario at which I would like to reload the menu.

I was wondering if I can make this process more automatic by broadcasting this event from the service on the $rootScope, and then listening to it in the controller.

Any thoughtsadvice on this will be greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

$watch() is doing dirt-checking: the function makes a comparison each digest cycle. On the other hand, $broadcast() propagates an event only when there is one. Naturally, $broadcast() is cheaper than $watch().

But did you really have to worry about performance here? One primitive comparison by cycle is nothing. However, conceptually, $watch() is clearly what you need: you want to do an action each time a variable changes. I can't imagine using $broadcast() here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...