简体   繁体   中英

decorating and accessing $rootScope method

I have decorated $rootScope in the config of module with a fn safeApply .

$provide.decorator('$rootScope', ['$delegate', function($delegate) {
        $delegate.safeApply = function(fn) {
           ...
         };
         return $delegate;
         }
]);

Is it ok to access it like

 $scope.$root.safeApply();

or do I need to inject $rootScope and then call it.

Can I add this method to the prototype of $rootScope so it will inherit in all $scope ? How to do this.

Edit

with khanh's response below, I may add bit more info. safeApply is a method used to trigger a digest cycle manually. The idea of decorating the $rootScope is from here https://coderwall.com/p/ngisma . Please see it in the comment. So, it is not decorating a method, more adding a functionality which is accessible across (scope of directive, controller)

Decorators should be used with services instead of scopes.

Decorator is a mechanism that allows use to wrap original service and performs cross-cutting concerns like: caching, logging,.. and leave the service intact to focus on its business without being polluted by these code.

I would implement the decorator like this. Let's say, we have a service defined in another module:

var lib = angular.module("lib",[]);
lib.service("util",function(){
     this.saveFile = function(file){
       console.log("save file:" + file);
     }
});

We need to use this service and decorate it with our code to do some logging without polluting the service with logging logic:

app.config(function($provide) {
  $provide.decorator('util', function($delegate) {

    var originalSaveFile = $delegate.saveFile;

    $delegate.saveFile = function(file){
       console.log("before save file");
       originalSaveFile.apply(this,arguments);
       console.log("after save file");
    }

    return $delegate;
  });
});

DEMO

Decorator is inspired from decorator pattern and aspect oriented programming

In your case, you could just add the function to $rootScope in module's run block and all scopes will inherit the function.

app.run(function($rootScope){
  $rootScope.safeApply = function(fn){
      console.log("safeApply");
  };
});

DEMO

We could also use decorator to do something like this, but it feels like it's not the right way as the idea of decorators is to create wrappers :

$provide.decorator('$rootScope', function($delegate) {

    $delegate.safeApply = function(fn){
      console.log("safe apply");
    }
    return $delegate;
  });

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM