jquery data cache (name, value) detailed and implemented

Source: Internet
Author: User
Tags tagname

I. The role of jquery data caching

The role of the jquery data cache is described in the Chinese API as follows: "The risk of accessing data on an element without circular references". How to understand this sentence, look at my example below, do not know if not fit, if you have a better example can tell me.

(1) There is an example of the risk of circular referencing (note the For in statement in the Getdatabyname (name) method):

<a href="javascript:void (0);"onclick="Showinfobyname (this.innerhtml);">Tom</a><br/> <a href="javascript:void (0);"onclick="Showinfobyname (this.innerhtml);">Mike</a> <script type="Text/javascript">varUserInfo = [      {          "name":"Tom",          " Age": +,          "Phone":"020-12345678"      },       {          "name":"Mike",          " Age": at,          "Phone":"020-87654321"      }    ]; function Getdatabyname (name) { for(varIinchuserInfo) {        if(Userinfo[i].name = =name) {          returnUserinfo[i];  Break; }}} function Showinfobyname (name) {varinfo =getdatabyname (name); Alert ('Name:'+ Info.name +'\ n'+'Age :'+ Info.age +'\ n'+'Phone:'+Info.phone); }  </script>

(2) Example of optimization of cyclic reference risk (this example is similar to the jquery cache implementation principle, this example focuses on rewriting the JSON structure of UserInfo, so that name and object key directly correspond):

<a href="javascript:void (0);"onclick="Showinfobyname (this.innerhtml);">tom</a><br/><a href="javascript:void (0);"onclick="Showinfobyname (this.innerhtml);">mike</a><script type="Text/javascript">varUserInfo = {      "Tom": {                "name":"Tom",                " Age": +,                "Phone":"020-12345678"              },      "Mike": {                "name":"Mike",                " Age": at,                "Phone":"020-87654321"              }      }; function Showinfobyname (name) {varinfo =Userinfo[name]; Alert ('Name:'+ Info.name +'\ n'+'Age :'+ Info.age +'\ n'+'Phone:'+Info.phone); }
Ii. simple implementation of jquery set data caching method

The implementation of the jquery data cache is actually very simple, let me implement jquery to set the data caching method, I make the code as simple as possible, which will help you more easily understand the implementation principle of data. The function and test code are as follows:

<div id="Div1">div1</div><br/><div id="Div2">div2</div><script type="Text/javascript">//The cache object is structured like this {"Uuid1": {"name1": value1, "name2": value2}, "Uuid2": {"name1": value1, "name2": value2}, Each UUID corresponds to a elem cache of data, each cached object can consist of multiple name/value pairs, and value can be of any data type, such as a JSON fragment can be stored in elem like this: $ (elem). Data (' JSON ': {" Name ":" Tom "," Age ": +})varCache = {};//expando as a new attribute of Elem, in order to prevent conflicts with the user's own definition, a variable suffix is used herevarexpando ='JQuery'+NewDate (). GetTime ();varUUID =0function Data (elem, name, data) {//at least Elem and name two parameters are guaranteed to be cached or set cache operation    if(Elem &&name) {        //try to take Elem label expando property        varID =Elem[expando]; if(data) {//setting up cached data            if(!ID) {ID= Elem[expando] = + +uuid;            } console.log (ID); //If the ID key object in the cache does not exist (that is, the Elem has not set the data cache), an empty object is created first            if(!Cache[id]) {Cache[id]= {}; Cache[id][name]=data; }        }Else{            //Get Cached Data            if(!ID) {return 'Not set cache!'; }Else{                returnCache[id][name]; }        }    }}vardiv = document.getElementById ('Div1');d ata (Div,"TagName","Div");d ata (Div,"ID","Div1"); alert (data (Div,"TagName"));//DivAlert (data (Div,"ID"));//Div1varDiv2 = document.getElementById ('Div2') alert (data (DIV2,"TagName"));//Not set cache!</script>
Third, use jquery data cache considerations

(1) Because the jquery cache object is global, in AJAX applications, because the page refreshes very little, this object will always exist, as you continue to manipulate data, it is likely because of improper use, so that the object is constantly growing, and ultimately affect program performance. So we have to clean up this object in time, and jquery provides the appropriate method: Removedata (name), name is the name parameter that you used when you set the data value.

In addition, based on my understanding of the jquery code, I found that there are several situations where you do not need to manually clear the data cache:

<1> performs a remove () operation on Elem, and jquery clears the cache that the object may exist. jquery related source code reference:

remove:function (selector) {if(!selector | | jquery.filter (SELECTOR, [ This]. length) {//Prevent Memory LeaksJQuery ("*", This). Add ([ This]). each (function () {jQuery.Event. Remove ( This); Jquery.removedata ( This);        }); if( This. parentnode) {             This. Parentnode.removechild ( This); }    }}

<2> performs an empty () operation on Elem, and if the current Elem child element has a data cache, jquery also clears the data cache that may exist for the child object, because the empty () implementation of jquery is actually a loop call to remove () to delete the child elements. jquery related source code reference:

empty:function () {    //  Remove ELEMENT nodes and prevent memory leaks    jQuery (this  ). Children (). remove ();     // Remove Any remaining nodes     while (this. FirstChild)          this. RemoveChild (this. firstchild);}

2. The JQuery replication node clone () method does not replicate the data cache, and it is accurate that jquery does not allocate a new node in the global cache object to hold the newly replicated Elem cache. jquery replaces the potentially existing cache pointer property (the Elem expando property) in Clone () with empty. If you copy this property directly, it will cause both the original and the newly copied elem to point to a data cache, and the intermediate interop will affect the cache variables of two elem. The following jquery code is to remove the expando attribute (jQuery1.3.2, which is not the case with earlier versions, and obviously the new version of this method performs better).

Jquery.clean ([Html.replace (/jquery\d+="(?: \ D+|null)"" "" ")] [0];

It is also useful to copy data caches, such as in a drag operation, when we click on the source target Elem node, we will copy a translucent copy of the Elem to start dragging and copy the data cache to the drag layer, and when the drag is over, we may take the Elem related information of the current drag. Now the jquery method does not provide us with such a treatment, how to do. The first approach is to rewrite the jquery code, which is obviously silly and unscientific. The correct approach is to copy the data from the source target and reset the data to the copied elem so that when the data (name, value) method is executed, jquery opens up new space for us in the global cache object. The implementation code is as follows:

if (typeof'number') {    var elemdata = $.cache[$.data ( Currentelement)];      for (var  in elemdata) {        dragingdiv.data (k, elemdata[k]);}    }

In the above code, $.data (Elem,name,data) contains three parameters, if there is only one elem parameter, this method returns its cache key (that is, UUID), the key can be used to obtain the entire cache object, and then the object's data are copied to the new object.

Webflash
Source: http://webflash.cnblogs.com

jquery data cache (name, value) detailed and implemented

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.