JQuery 2.0.3 Source Analysis data cache

Source: Internet
Author: User

Reprint http://www.cnblogs.com/aaronjs/p/3370176.html

Historical background:

jquery introduced the data cache system from version 1.2.3, the main reason is the early event system Dean Edwards's ddevent.js code

the problems brought by :

    • There is no caching mechanism for the system, it puts the callback of the event on top of the Eventtarget, which causes a circular reference
    • If Eventtarget is a Window object, it can also cause global pollution
    • Different cache variables for different modules

General jquery Development, we all like the convenience of a lot of attributes, such as state flags are written to the DOM node, that is HtmlElement

Benefits: Intuitive, convenient

Harm:

    • Circular references
    • Direct exposure to data, security?
    • Adding a bunch of custom attribute tags is meaningless to the browser
    • The HTML node should be manipulated when fetching data.

What is a memory leak

A memory leak refers to a piece of allocated memory that cannot be used or recycled until the browser process ends. In C + +, memory leaks are a frequent occurrence because of the manual management of memory. And now popular C # and Java and other languages use automatic garbage collection method to manage memory, in the case of normal use, there will be little memory leaks. The browser also uses the automatic garbage collection method to manage memory, but due to a bug in the browser garbage collection method, a memory leak occurs.

Several cases of memory leaks

    • Circular references
    • JavaScript closures
    • Dom Insertion Order

A DOM object is referenced by a JavaScript object while referencing the same or other JavaScript object, which can cause a memory leak. The reference to this DOM object will not be reclaimed by the garbage collector when the script is stopped. To break a circular reference, the reference to the object or DOM object referencing the DOM element needs to be assigned a value of NULL.

A circular reference with DOM objects will cause most of the current major browser memory leaks

First: multiple objects circular references

var a=new Object;  var b=New object;a.r=b;b.r=a;     

The second type: circular referencing yourself

var a=new object;a.r=a; 

Circular references are common and harmless in most cases, but circular references cause memory leaks when there are DOM objects or ActiveX objects in the object that participates in the circular reference.

A memory leak occurs when we replace any new object in the example with document.getElementById or document.createelement.

In-depth discussion of the specific, the summary here

    • JS memory leaks, no wonder is removed from the DOM element, but there are still variables or objects reference the DOM object. Then the memory cannot be deleted. Makes the browser's memory consumption high. This memory consumption, as the browser refreshes, will be automatically released.
    • In another case, a circular reference, a DOM object and the JS object are referenced to each other, which makes the situation more serious, even if the refresh, memory will not be reduced. This is the strict sense of memory leaks.

So in practical applications, we often need to cache some data for the elements, and these data are often closely related to DOM elements. Because DOM elements (nodes) are also objects, we can extend the properties of DOM elements directly, but if you add custom attributes and too much data to DOM elements that can cause memory leaks, you should try to avoid doing so. A better solution, therefore, is to use a low-coupling approach to connect the DOM with the cached data.

So we have to have a mechanism that abstracts out this kind of processing

The role of jquery in introducing caching

    • Allows us to append arbitrary types of data to DOM elements, avoiding the risk of memory leaks from circular references
    • Used to store data related to DOM nodes, including events, animations, etc.
    • A low-coupling way to connect the DOM to the cached data.
the real charm of the JQuery caching system lies in its internal application, where animations, events, and so on are all useful to this caching system. Imagine that if the animation's queue is stored in the custom properties of each DOM element, it makes it easy to access the queue data, but it also poses a hidden danger. If you add custom attributes and too much data to DOM elements that can cause a memory leak, try to avoid doing so.

Data Cache Interface

Jquery.data (element, key, value). Data ()

For the Jquery.data method, the original text is as follows

For a single element and retrieve them later:

In the official jquery documentation, prompt the user this is a low-level method that should be replaced with the. data () method. $.data (element, key, value) can append any type of data to a DOM element, but avoid a memory leak caused by circular references

are used to store data on the element as well as the usual data cache, all return jquery objects, but the internal processing is really the difference between the essential

Let's look at a set of comparisons

<div id= "Aaron" >aron test</div>
var aa1=$ ("#aaron");  var aa2=$ ("#aaron");  ======= First Group of =========    
$ (' '
). Data () method Aa1.data (' A ', 1111); Aa2.data (' A ', 2222); Aa1.data (' a ')  //// result 222222//= ====== second group =========$.data () method $.data (Aa1, "B", "1111") $.data (Aa2, "B", "2222"//// result 222222 

Was it an accident? , is this detail noticed before?

How does the. Data () method overwrite the same value as the previous key?

For jquery, the data caching system was originally differentiated for the Event system service, and later, its event cloning and even later animation queue to achieve the storage of data is inseparable from the cache system, so the data cache is a core of jquery is the basis of

Early jquery's caching system was to put all the data on top of the $.cache, and then for each element node to use the cache system, the Document object and the Window object were assigned a UUID

Data is not implemented as attr directly to the element node, if data is appended to the DOM elements, and DOM element is an object, but IE6, IE7 has problems with the garbage collection of objects directly attached to the DOM element; We store this data in the global cache (What we call "Globalcache"), where "Globalcache" contains the "cache" of multiple DOM element and adds a property on the DOM element that holds the corresponding UID for "cache"

$ (). Data (' a ') is in the form of expression, although it is associated to the DOM, but in fact processing is to open up a cache of caches in the memory area.

So how does jquery handle all the related situations and operations?

$ ('). How the data () is implemented ********************

Attaching data to an object with name and value

var obj = {};        $.data (obj, ' name ', ' Aaron ');    //Aaron   

An object attaches data to an object

var obj = {};    $.data (obj, {        name1: ' Aaron1 ',        name2: ' Aaron1 '    });    $.data (obj)   //Object {name1: "Aaron1", Name2: "Aaron1"}    

Attaching data to DOM Element

We use the simplest code to illustrate the process of this process:

1. Get the node body

var $body = $ ("Body")

2. Add a piece of data to the body, the property is Foo, and the value is 52

$body. Data ("foo", 52);

3. Remove Foo

$body. Data (' foo ')

Consider a problem:

An element can normally be removed by using the. Remove () method, and the respective data is purged. However, for local objects, this cannot be completely deleted, and these related data persist until the Window object is closed

Again, these problems exist in the event object because the event handler (handlers) is also stored in this method.

The simplest way to solve the problem is to store the data in one of the new properties of the local object

So add a unlock tag like process two parsing

The cache and the Elem are unified.

If (elem.nodetype) {        cache[id] = dataObject;             elem[expando] = ID;    else {elem[expando] = dataObject;}     

Implementing parsing ****************

(1) First create a cache object {}inside jquery to save the cached data. Then extend a property that has a value of expando on the DOM node where it needs to be cached.

function Data () {    This.cache = {}, 0, {        functionreturnThis.expando = Jquery.expando +< c11> math.random ();}      

Note: The value of expando, which is used to make a node property of the current data cache's UUID value, is written to the specified element to form an associated bridge, so the element itself has little likelihood of having this attribute, so the conflict can be ignored.

(2) Then set the value of each node's Dom[expando] to a self-increment variable ID, maintaining global uniqueness. The value of this ID is used as the key of the cache to correlate DOM nodes and data. That is, Cache[id] takes all the caches on this node, the ID is like the key to open a room (DOM node). All caches of each element are placed in a map map so that multiple data can be cached at the same time.

Data.uid = 1;

An index tag that associates a DOM object with a data cache object, in other words

Find the expando corresponding value on the DOM element, and then the UID, and then find the contents of the data cache object through this UID

(3) So the cache object structure should look like this:

var cache = {    /// DOM node 1 cached data,        "Name1": value1,        "name2"// DOM node 2 cache data, "name1"  : value1, "name2"// ...};        

Each UID corresponds to a elem cache of data, and each cached object can consist of multiple name/value (name-value pairs) pairs , and value can be of any data type .

Process decomposition: (complex filtration, the process of looking for weight removed)

The first step: jquery itself is the wrapped array structure, this does not need to parse the

Second Step: Data storage

    • The data is stored on a cache object in order to not associate the data directly with the DOM
    • produce a unlock = data.uid++; Unlock tag number
    • Assign the unlock tag number as a property value to the $body node
    • The cache cache object opens up a new space for storing Foo data, this.cache[unlock] = {};
    • Finally, the Foo data is hung on the cache, cache["= value";

Step Three: Data acquisition

    • Get the unlock tag from the $body node
    • To fetch the corresponding data in the cache via unlock

Flow chart:

The whole process is over, in fact, after the decomposition of logic is very simple, just to deal with a variety of situations, the code structure encapsulation is very complex


BODY element: Expando:uid

Jquery203054840829130262140.37963378243148327:3

Data caching cache

Uid:object

So what's the difference between Jquery.data () and. Data ()?

1.jquery.data (Element,[key],[value]) source code

Jquery.extend ({        acceptData:Data.accepts,        function(elem) {},       // call directly data_user.access The interface of the data class, which is passed elem the entire jquery object        functionreturn data_user.access (elem, name, data);}, ...  


2.data ([Key],[value])

JQuery.fn.extend ({function        (elem, name, data) {            function//This.each (function () { } } } }, ........


Source code from the source of a simple comparison is obvious to see

    • See Jquery.data (Element,[key],[value]), each element will have its own {Key:value} object holds the data, So the new object will not overwrite the value corresponding to the original object key, even if it has the same key, because the new object is saved in another {Key:value} object
    • $ ("div"). Data ("A", "AAAA") it is on the elements that bind each of the DIV nodes

Source can be seen, in the final analysis, the data cache is in the target object and cache to establish a one-to-one relationship, the entire data class is actually around the Thia.cache internal data to do additions and deletions to the operation of the search

JQuery 2.0.3 Source Analysis data cache

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.