博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
AngularJS' Internals In Depth(深入理解 AngularJS)
阅读量:7080 次
发布时间:2019-06-28

本文共 19650 字,大约阅读时间需要 65 分钟。

hot3.png

AngularJS presents a remarkable number of interesting design choices in its code base. Two particularly interesting cases are the way in which scopes work and how directives behave.

The first thing anyone is taught when approaching AngularJS for the first time is that directives are meant to interact with the DOM, or whatever manipulates the DOM for you, such as jQuery (!). What immediately becomes (and remains) confusing for most, though, is the interaction between scopes, directives and controllers.

After the confusion sets in, you start learning about the advanced concepts: the digest cycle, isolate scopes, transclusion and the different linking functions in directives. These are mind-blowingly complex as well. I won’t cover directives in this article, but they’ll be addressed in its follow-up.

This article will navigate the salt marsh that is AngularJS scopes and the lifecycle of an AngularJS application, while providing an amusingly informative, in-depth read.

(The bar is high, but scopes are sufficiently hard to explain. If I’m going to fail miserably at it, at least I’ll throw in a few more promises I can’t keep!)

If the following figure looks unreasonably mind-bending, then this article might be for you.

( ) ( )

(Disclaimer: This article is based on .)

AngularJS uses scopes to abstract communication between directives and the DOM. Scopes also exist at the controller level. Scopes are plain old JavaScript objects (POJO) that AngularJS does not heavily manipulate. They only add a bunch of “internal” properties, prefixed with one or two $ symbols. The ones prefixed with $$ aren’t necessary as frequently, and using them is often a code smell, which can be avoided by having a deeper understanding of the digest cycle.

What Kind Of Scopes Are We Talking About?

In AngularJS slang, a “scope” is not what you might be used to when thinking about JavaScript code or even programming in general. Usually, scopes are used to refer to the bag in a piece of code that holds the context, variables and so on.

(In most languages, variables are held in imaginary bags, which are defined by curly braces ({}) or code blocks. This is known as “.” JavaScript, in contrast, deals in “,” which pretty much means that the bags are defined by functions, or the global object, rather than by code blocks. Bags may contain any number of smaller bags. Each bag can access the candy (sweet, sweet variables) inside its parent bag (and in its parent’s parent, and so on), but they can’t poke holes in smaller, or child, bags.)

As a quick and dirty example, let’s examine the function below.

function eat (thing) {   console.log('Eating a ' + thing);}function nuts (peanut) {   var hazelnut = 'hazelnut';   function seeds () {      var almond = 'almond';      eat(hazelnut); // I can reach into the nuts bag!   }   // Almonds are inaccessible here.   // Almonds are not nuts.}

I won’t dwell on  any longer, because these are not the scopes people refer to when talking about AngularJS. Refer to “” if you’d like to learn more about scopes in the context of the JavaScript language.

SCOPE INHERITANCE IN ANGULARJS

Scopes in AngularJS are also context, but on AngularJS’ terms. In AngularJS, a scope is associated with an element (and all of its child elements), while an element is not necessarily directly associated with a scope. Elements are assigned a scope is one of the following three ways.

The first way is if a scope is created on an element by a controller or a directive (directives don’t always introduce new scopes).

Secondly, if a scope isn’t present on the element, then it’s inherited from its parent.

   
Click Me! 

Thirdly, if the element isn’t part of an ng-app, then it doesn’t belong to a scope at all.

   

Pony Deli App

   
      
Click Me!   

To figure out an element’s scope, try to think of elements recursively inside outfollowing the three rules I’ve just outlined. Does it create a new scope? That’s its scope. Does it have a parent? Check the parent, then. Is it not part of an ng-app? Tough luck — no scope.

You can (and most definitely should) use the magic of developer tools to easily figure out the scope of an element.

PULLING UP ANGULARJS’ INTERNAL SCOPE PROPERTIES

I’ll walk through a few properties in a typical scope to introduce certain concepts, before moving on to explaining how digests work and behave internally. I’ll also let you in on how I get to these properties. First, I’ll open Chrome and navigate to the application I’m working on, which is written in AngularJS. Then, I’ll inspect an element and open the developer tools.

(Did you know that  in the “Elements” pane? $1 gives you access to the previously selected element, and so on. I prognosticate that you’ll use $0 the most, particularly when working with AngularJS.)

For any given DOM element, angular.element wraps that in either  or jqLite, jQuery’s . Once it’s wrapped, you get access to a scope() function that returns — you guessed it! — the AngularJS scope associated with that element. Combining that with $0, I find myself using the following command quite often.

angular.element($0).scope()

(Of course, if you know that you’ll be using jQuery, then $($0).scope() will work just the same. And angular.element works every time, regardless of whether jQuery is available.)

Then, I’m able to inspect the scope, assert that it’s the scope I expected, and assert whether the property’s values match what I was expecting. Super-useful! Let’s see what special properties are available in a typical scope, those prefixed with one or more dollar signs.

for(o in $($0).scope())o[0]=='$'&&console.log(o)

That’s good enough. I’ll go over all of the properties, clustering them by functionality, and go over each portion of AngularJS’ scoping philosophy.

Examining A Scope’s Internals In AngularJS

Below, I’ve listed the properties yielded by that command, grouped by area of functionality. Let’s start with the basic ones, which merely provide scope navigation.

  • uniquely identifies the scope

  • root scope

  • parent scope, or null if scope == scope.$root

  • first child scope, if any, or null

  • last child scope, if any, or null

  • previous sibling scope, if any, or null

  • next sibling scope, if any, or null

No surprises here. Navigating scopes like this would be utter nonsense. Sometimes accessing the $parent scope might seem appropriate, but there are always better, less coupled, ways to deal with parental communication than by tightly binding people scopes together. One such way is to use event listeners, our next batch of scope properties!

EVENT MODEL IN ANGULARJS SCOPE

The properties described below enable us to publish events and subscribe to them. This is a pattern known as , or just events.

  • event listeners registered on the scope

  • attaches an event listener fn named evt

  • fires event evt, roaring upward on the scope chain, triggering on the current scope and all $parents, including the $rootScope

  • fires event evt, triggering on the current scope and all of its children

When triggered, event listeners are passed an event object and any arguments passed to the $emit or $broadcast function. There are many ways in which scope events can provide value.

A directive might use events to announce that something important has happened. Check out the sample directive below, where a button can be clicked to announce that you feel like eating food of some type.

angular.module('PonyDeli').directive('food', function () {   return {      scope: { // I'll come back to directive scopes later         type: '=type'      },      template: '
I want to eat some {
{type}}!',      link: function (scope, element, attrs) {         scope.eat = function () {            letThemHaveIt();            scope.$emit('food.order, scope.type, element);         };         function letThemHaveIt () {            // Do some fancy UI things         }      }   };});

I namespace my events, and so should you. It prevents name collisions, and it makes clear where events originate from or what event you’re subscribing to. Imagine you have an interest in analytics and want to track clicks on food elements using . That would actually be a reasonable need, and there’s no reason why that should be polluting your directive or your controller. You could put together a directive that does the food-clicking analytics-tracking for you, in a nicely self-contained manner.

angular.module('PonyDeli').directive('foodTracker', function (mixpanelService) {   return {      link: function (scope, element, attrs) {         scope.$on('food.order, function (e, type) {            mixpanelService.track('food-eater', type);         });      }   };});

The service implementation is not relevant here, because it would merely wrap Mixpanel’s client-side API. The HTML would look like what’s below, and I’ve thrown in a controller to hold all of the food types that I want to serve in my deli. The directive helps AngularJS to auto-bootstrap my application as well. Rounding out the example, I’ve added an ng-repeat directive so that I can render all of my food without repeating myself; it’ll just loop through foodTypes, available on foodCtrl’s scope.

   
angular.module('PonyDeli').controller('foodCtrl', function ($scope) {   $scope.foodTypes = ['onion', 'cucumber', 'hazelnut'];});

The fully working example is .

That’s a good example on paper, but you need to think about whether you need an event that anyone can subscribe to. Maybe a service will do? In this case, it could go either way. You could argue that you’ll need events because you don’t know who else is going to subscribe to food.order, which means that using events would be more future-proof. You could also say that the food-tracker directive doesn’t have a reason to be, because it doesn’t interact with the DOM or even the scope at all other than to listen to an event, which you could replace with a service.

Both thoughts would be correct, in the given context. As more components need to befood.order-aware, then it might feel clearer that events are the way to go. In reality, though, events are most useful when you actually need to bridge the gap between two (or more) scopes and other factors aren’t as important.

As we’ll see when we inspect directives more closely in the upcoming second part of this article, events aren’t even necessary for scopes to communicate. A child scope may read from its parent by binding to it, and it may also update those values.

(There’s rarely a good reason to host events to help children communicate better with their parents.)

Siblings often have a harder time communicating with each other, and they often do so through a common parent. That generally translates into broadcasting from $rootScopeand listening on the siblings of interest, as below.

   
      
         
            
I want to eat that!      
      
         A monkey has been dispatched. You shall eat soon.         angular.module('PonyDeli').controller('foodCtrl', function ($rootScope) {   $scope.foodTypes = ['onion', 'cucumber', 'hazelnut'];   $scope.deliver = function (req) {      $rootScope.$broadcast('delivery.request', req);   };});angular.module('PonyDeli').controller('deliveryCtrl', function ($scope) {   $scope.$on('delivery.request', function (e, req) {      $scope.received = true; // deal with the request   });});

This one is .

Over time, you’ll learn to lean towards events or services accordingly. I could say that you should use events when you expect view models to change in response to eventand that you ought to use services when you don’t expect changes to view models. Sometimes the response is a mixture of both: an action triggers an event that calls a service, or a service that broadcasts an event on $rootScope. It depends on the situation, and you should analyze it as such, rather than attempting to nail down the elusive one-size-fits-all solution.

If you have two components that communicate through $rootScope, then you might prefer to use $rootScope.$emit (rather than $broadcast) and $rootScope.$on. That way, the event would only spread among $rootScope.$$listeners, and it wouldn’t waste time looping through every child of $rootScope, which you just know won’t have any listeners for that event. Below is an example service using $rootScope to provide events without limiting itself to a particular scope. It provides a subscribe method that allows consumers to register event listeners, and it might do things internally that trigger that event.

angular.module('PonyDeli').factory("notificationService", function ($rootScope) {   function notify (data) {      $rootScope.$emit("notificationService.update", data);   }   function listen (fn) {      $rootScope.$on("notificationService.update", function (e, data) {         fn(data);      });   }   // Anything that might have a reason   // to emit events at later points in time   function load () {      setInterval(notify.bind(null, 'Something happened!'), 1000);   }   return {      subscribe: listen,      load: load   };});

You guessed right! This one is .

Enough events-versus-services banter. Shall we move on to some other properties?

DIGESTING CHANGESETS

Understanding this intimidating process is the key to understanding AngularJS.

AngularJS bases its data-binding features in a and fires events when these change. This is simpler than it sounds. No, really. It is! Let’s quickly go over each of the core components of the $digest cycle. First, there’s thescope.$digest method, which recursively digests changes in a scope and its children.

  1. executes the $digest dirty-checking loop

  2. current phase in the digest cycle, one of [null, '$apply', '$digest']

You need to be careful about triggering digests, because attempting to do so when you’re already in a digest phase would cause AngularJS to blow up in a mysterious haze of unexplainable phenomena. In other words, pinpointing the root cause of the issue would be pretty hard.

Let’s look at  about $digest.

Processes all of the  of the current scope and its children. Because a’s listener can change the model, the  keeps calling the until no more listeners are firing. This means that it is possible to get into an infinite loop. This function will throw 'Maximum iteration limit exceeded.' if the number of iterations exceeds 10.

Usually, you don’t call  directly in  or in . Instead, you should call  (typically from within a ), which will force a.

So, a $digest processes all watchers, and then processes the watchers that those watchers trigger, until nothing else triggers a watch. Two questions remain to be answered for us to understand this loop.

  • What the hell is a “watcher”?!

  • What triggers a $digest?!

The answers to these questions vary wildly in terms of complexity, but I’ll keep my explanations as simple as possible so that they’re clear. I’ll begin talking about watchers and let you draw your own conclusions.

If you’ve read this far, then you probably already know what a watcher is. You’ve probably used , and maybe even used . The$$watchers property has all of the watchers on a scope.

  • adds a watch listener to the scope

  • watches array items or object map properties

  • contains all of the watches associated with the scope

Watchers are the single most important aspect of an AngularJS application’s data-binding capabilities, but AngularJS needs our help in order to trigger those watchers; otherwise, it can’t effectively update data-bound variables appropriately. Consider the following example.

   
      
      
   angular.module('PonyDeli').controller('foodCtrl', function ($scope) {   $scope.prop = 'initial value';   $scope.dependency = 'nothing yet!';   $scope.$watch('prop', function (value) {      $scope.dependency = 'prop is "' + value + '"! such amaze';   });   setTimeout(function () {      $scope.prop = 'something else';   }, 1000);});

So, we have 'initial value', and we’d expect the second HTML line to change to'prop is "something else"! such amaze' after a second, right? Even more interesting, you’d at the very least expect the first line to change to 'something else'! Why doesn’t it? That’s not a watcher… or is it?

Actually, a lot of what you do in the HTML markup ends up creating a watcher. In this case,  on the property. It will update the HTML of the <li> whenever prop and dependency change, similar to how our watch will change the property itself.

This way, you can now think of your code as having three watches, one for each ng-bind directive and the one in the controller. How is AngularJS supposed to know that the property is updated after the timeout? You could remind AngularJS of an update to the property by adding a manual digest to the timeout callback.

setTimeout(function () {   $scope.prop = 'something else';   $scope.$digest();}, 1000);

I’ve set up a CodePen , and one that  after the timeout. The more  to do it, however, would be to use the  instead of setTimeout. It provides some error-handling, and it executes$apply().

$timeout(function () {   $scope.prop = 'something else';}, 1000);
  • parses and evaluates an expression and then executes the $digest loop on$rootScope

In addition to executing the digest on every scope, $apply provides error-handling functionality as well. If you’re trying to tune performance, then using $digest might be warranted, but I’d stay away from it until you feel really comfortable with how AngularJS works internally. One would actually need to call $digest() manually very few times;$apply is almost always a better choice.

We’re back to the second question now.

  • What triggers a $digest?!

Digests are triggered internally in strategic places all over AngularJS’ code base. They are triggered either directly or by calls to $apply(), like we’ve observed in the $timeoutservice. Most directives, both those found in AngularJS’ core and those out in the wild, trigger digests. Digests fire your watchers, and watchers update your UI. That’s the basic idea anyway.

You will find a pretty good resource with best practices in the AngularJS wiki, which is linked to at the bottom of this article.

I’ve explained how watches and the $digest loop interact with each other. Below, I’ve listed properties related to the $digest loop that you can find on a scope. These help you to parse text expressions through AngularJS’ compiler or to execute pieces of code at different points in the digest cycle.

  • parse and evaluate a scope expression immediately

  • parse and evaluate an expression at a later point in time

  • async task queue, consumed on every digest

  • executes fn after the next digest cycle

  • methods registered with $$postDigest(fn)

Phew! That’s it. It wasn’t that bad, was it?

THE SCOPE IS DEAD! LONG LIVE THE SCOPE!

Here are the last few, rather dull-looking, properties in a scope. They deal with the scope’s life cycle and are mostly used for internal purposes, although you may want to$new scopes by yourself in some cases.

  • isolate scope bindings (for example, { options: '@megaOptions' } — very internal

  • creates a child scope or an isolate scope that won’t inherit from its parent

  • removes the scope from the scope chain; scope and children won’t receive events, and watches won’t fire anymore

  • has the scope been destroyed?

Isolate scopes? What is this madness? The second part of this article is dedicated to directives, and it covers isolate scopes, transclusion, linking functions, compilers, directive controllers and more. Wait for it!

转载于:https://my.oschina.net/jellypie/blog/486338

你可能感兴趣的文章
Apache和Nginx的区别
查看>>
2017.5.23 MS Power BI workshop for partner
查看>>
翻译连载 |《你不知道的JS》姊妹篇 |《JavaScript 轻量级函数式编程》- 第 8 章:列表操作...
查看>>
Linux常用的系统监控shell脚本
查看>>
Android Studio中使用GreenDao
查看>>
Yii 框架之采用自带的jquery库实现ajax分页
查看>>
负载均衡小demo,未实现session共享
查看>>
Android广播-个人总结
查看>>
redis java客户端Jedis 实现 连接池 + 简单的负载均衡
查看>>
python的string.strip(s[, chars])方法的各种小细节
查看>>
new Date() 在Safari下的 Invalid Date问题
查看>>
Mac OSX升级10.14后,sequel pro关闭时闪退crash解决办法
查看>>
Mybatis 框架源码分析
查看>>
关于 LF will be replaced by CRLF 问题出现的原因以及解决方式
查看>>
HTML5编程之旅 第3站 WebSockets
查看>>
oracle 体系结构及内存管理 05_重建EM
查看>>
everedit
查看>>
改写源代码,使得认证成功后跳转到successUrl路径
查看>>
浅析CentOS和RedHat Linux的区别
查看>>
Linux gcc版本如何升级
查看>>