Build your own AngularJS (1): Scope and Digest (1)

Source: Internet
Author: User
Tags angular scope

Angular is a mature and powerful JavaScript framework. It is also a relatively large framework. Before mastering it, you need to understand many new concepts it has proposed. Many Web developers flock to Angular, and many face the same obstacles. How did Digest do it? Define a directive direve VE) What are the different methods? What is the difference between Service and provider?

Angular's documentation is quite good, and third-party resources are becoming richer and richer. To learn a new technology, there is no better way than to take it apart and study its operating mechanism.

In this series of articles, I will build an implementation of AngularJS from scratch. With more and more in-depth explanations, readers will be able to have a deep understanding of Angular's operating mechanism.

In the first part, the reader will see how Angular's scope works, and how to implement such things as $ eval, $ digest, and $ apply. Angular's dirty check logic looks incredible, but you will see that this is not the case.

Basic knowledge

On Github, you can see all the source code of this project. Compared with copying only one copy, I suggest you build your own implementations from scratch and explore every step of the code from different perspectives. In this article, I have embedded some JSBin code and can interact directly in the article. Note: Because I have translated JSBin on github, I cannot integrate JSBin. I can only give links ......)

We will use the Lo-Dash library to process some underlying operations on arrays and objects. Angular itself does not use Lo-Dash, but for our purposes, we should try to ignore these irrelevant underlying things. When the reader sees the underscore _) in the code, it is calling the Lo-Dash function.

We will also use the console. assert function for some special tests. This function should be applicable to all modern JavaScript environments.

The following is an example of using the Lo-Dash and assert functions:

Http://jsbin.com/UGOVUk/4/embed? Js, console

Scope object

Angular Scope objects are simple JavaScript objects in POJO. On these objects, attributes can be added just like other objects. The Scope object is created using constructors. Let's write the simplest version:

 
 
  1. function Scope() { 

Now we can use the new operator to create a Scope object. We can also add some attributes on it:

 
 
  1. var aScope = new Scope(); 
  2. aScope.firstName = 'Jane'; 
  3. aScope.lastName = 'Smith'; 

These attributes are nothing special. There is no need to call a special setter), and there is no limit when assigning values. On the contrary, there are two special functions: $ watch and $ digest.

Monitored object attributes: $ watch and $ digest

$ Watch and $ digest complement each other. The two constitute the core of Angular scope: Response to data changes.

With $ watch, you can add a listener on the Scope. When the Scope changes, the listener will receive a prompt. You can create a listener by specifying the following two functions for $ watch:

  • A monitoring function is used to specify the part of data to be followed.
  • A listener function is used to receive a prompt when the data is changed.

As an Angular user, an expression is monitored rather than a monitoring function. A monitoring expression is a string, such as "user. firstName", which is usually specified in data binding, command attributes, or JavaScript code. It is parsed and compiled into a monitoring function by Angular. Later in this article, we will discuss how this is done. In this article, we will use a slightly lower-level method to directly provide the monitoring function.

To implement $ watch, we need to store all registered listeners. We add an array to the Scope constructor:

 
 
  1. function Scope() { 
  2.   this.$$watchers = []; 

In the Angular framework, the double dollar prefix $ indicates that the variable is considered as private and should not be called in external code.

Now we can define the $ watch method. It accepts two functions as parameters and stores them in the $ watchers array. We need to store these functions on each Scope instance, so we need to put them on the prototype of Scope:

 
 
  1. Scope.prototype.$watch = function(watchFn, listenerFn) { 
  2.   var watcher = { 
  3.     watchFn: watchFn, 
  4.     listenerFn: listenerFn 
  5.   }; 
  6.   this.$$watchers.push(watcher); 
  7. }; 

The other side is the $ digest function. It executes all listeners registered in the scope. Let's implement a simplified version of it, traverse all the listeners, and call their listening functions:

 
 
  1. Scope.prototype.$digest = function() { 
  2.   _.forEach(this.$$watchers, function(watch) { 
  3.     watch.listenerFn(); 
  4.   });  
  5. }; 

Now we can add a listener and run $ digest. This will call the listener function:

Http://jsbin.com/oMaQoxa/2/embed? Js, console

These functions are useless. We need to check whether the value specified by the monitoring function has actually changed and then call the monitoring function.

Dirty checking

As mentioned above, the listener's listening function should return the changes of the part of data we are concerned with. Normally, this part of data exists in the scope. To make the access scope more convenient, the current scope is used as the real parameter when the monitoring function is called. A listener that focuses on the fiestName attribute in the scope looks like this:

 
 
  1. function(scope) { 
  2.   return scope.firstName; 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.