JQuery data cache (name, value) detailed and implementation _jquery

Source: Internet
Author: User
Tags tagname uuid
As a programmer, a reference to "caching" can easily be associated with "client (browser caching)" and "Server Caching". Client-side caching is the browser temporary folder on the computer's hard disk, and the server cache exists in the server's memory, and of course there are special caching servers in some advanced applications, even the implementation of caching using the database. Of course, none of this is in the scope of this article, this article discusses the most popular JavaScript framework jquery data caching implementation principles, this is the jQuery1.2.3 version began to add new features.
I. The role of jquery data caching
The role of the jquery data cache is described in the Chinese API: "Access to data on one element avoids the risk of circular references". How to understand this sentence, look at my below examples, do not know fit, if you have a better example can tell me.
(1) There is an example of a circular reference risk (note the for in statement in the Getdatabyname (name) method):
Copy Code code as follows:

<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" >
var userInfo = [
{
"Name": "Tom",
"Age": 21,
"Phone": "020-12345678"
},
{
"Name": "Mike",
"Age": 23,
"Phone": "020-87654321"
}];
function Getdatabyname (name)
{
for (var i in UserInfo)
{
if (userinfo[i].name = = name)
{
return userinfo[i];
Break
}
}
}
function Showinfobyname (name)
{
var info = getdatabyname (name);
Alert (' Name: ' + info.name + ' \ n ' + ' Age: ' + info.age + ' \ n ' + ' phone: ' + info.phone ');
}
</script>

(2) The example of optimizing the cyclic reference risk (This example is actually similar to the jquery caching implementation principle, this example focuses on rewriting the JSON structure of userinfo so that name corresponds directly to the object key):
Copy Code code as follows:

<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" >
var userInfo =
{
"Tom":
{
"Name": "Tom",
"Age": 21,
"Phone": "020-12345678"
},
"Mike":
{
"Name": "Mike",
"Age": 23,
"Phone": "020-87654321"
}
};
function Showinfobyname (name)
{
var info = Userinfo[name];
Alert (' Name: ' + info.name + ' \ n ' + ' Age: ' + info.age + ' \ n ' + ' phone: ' + info.phone ');
}
</script>

Two, simple realization jquery set up data caching method
The implementation of the jquery data cache is actually very simple, I will implement the jquery data caching method, I let the code as simple as possible, which will help you easier to understand the implementation of data. The function and test code are as follows:
Copy Code code as follows:

<div id= "Div1" >div1</div><br/>
<div id= "Div2" >div2</div>
<script type= "Text/javascript" >
Cache object structure 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 be composed of multiple name/value pairs, and value can be of any data type, for example, you can save a JSON fragment like this in Elem: $ (elem). Data (' JSON ': {" Name ": Tom", "Age": 23})
var cache = {};
Expando as a new addition to the Elem property, in order to prevent conflicts with the user's own definition, the variable suffix is used here
var expando = ' jQuery ' + new Date (). GetTime ();
var uuid = 0;
function data (elem, name, data)
{
At a minimum, elem and name two parameters are required to cache or set cache operations
if (elem && name)
{
Attempt to fetch Elem label expando property
var id = Elem[expando];
if (data)
{
Setting cached data
if (!id)
id = Elem[expando] = ++uuid;
If the ID key object in the cache does not exist (that is, the elem does not have a data cache set), create an empty object first
if (!cache[id])
Cache[id] = {};
Cache[id][name] = data;
}
Else
{
Get Cached data
if (!id)
Return ' not set cache! ';
Else
return Cache[id][name];
}
}
}
var div = document.getElementById (' Div1 ');
Data (Div, "tagName", "div");
Data (Div, "ID", "Div1");
Alert (data (Div, "tagName")); Div
Alert (data (Div, "ID")); Div1
var div2 = document.getElementById (' div2 ');
Alert (Data (Div2, "tagName")); Not set cache!
</script>

iii. using jquery data caching 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 operate on the data, it is likely because of the use of improper, so that the object continues to become larger, ultimately affecting program performance. So we need to clean up the object in time, and jquery also provides the appropriate method: Removedata (name), which is the name parameter you used when you set the data value.
Also, based on my understanding of the jquery code, there are several situations where you do not need to manually clear the data cache:
<1> perform a remove () operation on Elem, jquery clears the cache that the object may exist. jquery related source code reference:
Copy Code code as follows:

Remove:function (selector)
{
if (!selector | | jquery.filter (SELECTOR, [this]). Length)
{
Prevent memory leaks
JQuery ("*", this). Add ([this]). each (function ()
{
JQuery.event.remove (this);
Jquery.removedata (this);
});
if (This.parentnode)
This.parentNode.removeChild (this);
}
}

<2> performs empty () operations on Elem, and jquery clears the possible data caches of child objects if there is a data cache for the current Elem child element, since the empty () implementation of jquery is actually a circular call to remove () Delete child elements. jquery related source code reference:
Copy Code code as follows:

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 true that jquery does not allocate a new node in the global cache object to store the new replication Elem cache. jquery replaces the possible cache-pointing attribute (Elem's expando attribute) in clone () to NULL. If you copy this attribute directly, it will cause both the original and newly replicated elem to point to a data cache, and the middle interop will affect the two Elem cache variables. The following jquery code is the deletion of the expando attribute (jQuery1.3.2, which is not handled in earlier versions, and is obviously better for this new version).
Jquery.clean ([Html.replace (/jquery\d+=) (?: \ D+|null) "/g," "). Replace (/^\s*/," ")]) [0];
It is sometimes useful to copy the data cache together, for example, in the drag operation, we click on the source target Elem node will copy a translucent elem copy start to drag, and the data cache copied to the drag layer, wait until the drag end, we can take the current drag Elem related information. Now the jquery method does not provide us with such a deal, how to approach. The first option is to rewrite the jquery code, which is clearly silly and unscientific. The correct approach is to copy the data from the source target and reset the data to the replicated elem so that jquery will open up new space for us in the global cache object when executing the data (name, value) method. The implementation code is as follows:
Copy Code code as follows:

if (typeof ($.data (currentelement)) = = ' number ')
{
var elemdata = $.cache[$.data (currentelement)];
For (var k in Elemdata)
{
Dragingdiv.data (k, elemdata[k]);
}
}

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

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.