Why using $rootScope with functions is not recommended?

前端 未结 3 678
别跟我提以往
别跟我提以往 2020-11-28 15:58

While am looking into the FEQs of Angularjs I\'ve seen below article:

$rootScope exists, but it can be used for evil

Scopes in An

3条回答
  •  悲&欢浪女
    2020-11-28 16:38

    There exist no performance issues. It would actually boost your performance by a fraction of time, because you dont need to dependency-inject a lot of services.

    But it's a big concern of design. Consider a large application with dozens and dozens of views, complex components and tied to a number of well known APIs (e.g. Twitter, Flickr, Facebook, OAuth, ...).

    You wont develop this application alone. The following issues will arise:

    Namespacing

    You are working on the Facebook API, someone else is working on the Twitter API. You both think that using $rootScope for functions is a good idea and both write a $rootScope.login function. How would you resolve this when doing git merge? You need namespacing, alas, you need to develop two services myFacebookAPI, myTwitterAPI which then can implement the same interface for loggin in. (login(user,pw)). Note that this gives you the ability to abstract away the actual social network you are dealing with in the controller, when you can do something like:

    $scope.callAction = function (action) {
    var service;
        if ($scope.serviceSelected === 'fb') {
             service = myFacebookAPI;
        } else {
             service = myTwitterAPI;
        }
        service[action]();
    };
    

    Testing

    When developing professionally, you write tests. Angular gives you tools to do automated tests for services, etc., but you wont be able to test something you assign to $rootScope in the same comfortable manner.

    Other issues will arise too, but i think this should be enough for you to think about it on your own.

提交回复
热议问题