什么是“便宜”的性能代价$广播或收看$ [英] What is 'cheaper' performance-wise $broadcast or $watch

查看:109
本文介绍了什么是“便宜”的性能代价$广播或收看$的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序的情况下,我需要每次都重新加载菜单的用户更改角色(一个用户可以在几家公司的角色)。

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.

目前我做以下内容:

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.

有什么想法\\此建议将大大AP preciated。

Any thoughts\advice on this will be greatly appreciated.

推荐答案

$腕表()正在做污垢检查:功能使得comparaison每个消化周期。在另一方面, $广播()只有当有一个传播的事件。当然, $广播() $便宜腕表()

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

但你真的要在这里担心性能?通过循环一个原始comparaison什么。不过,从概念上讲, $腕表()显然你需要:你想要做一个动作的每次一个变量的变化。我无法想象使用 $广播()在这里。

But did you really have to worry about performance here? One primitive comparaison 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.

这篇关于什么是“便宜”的性能代价$广播或收看$的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆