什么是“更便宜"的性能明智的 $broadcast 或 $watch [英] 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.
我想知道是否可以通过从 $rootScope 上的服务广播此事件,然后在控制器中侦听它来使此过程更加自动化.
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 thoughts\advice on this will be greatly appreciated.
推荐答案
$watch()
正在进行污垢检查:该函数在每个摘要周期进行比较.另一方面,$broadcast()
仅在有事件时传播事件.自然,$broadcast()
比 $watch()
便宜.
$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()
.
但是你真的需要担心这里的性能吗?一种按周期进行的原始比较算不了什么.但是,从概念上讲,$watch()
显然是您所需要的:您希望每次变量更改时执行一个操作.我无法想象在这里使用 $broadcast()
.
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.
这篇关于什么是“更便宜"的性能明智的 $broadcast 或 $watch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!