Home > Web Front-end > JS Tutorial > body text

Detailed explanation and implementation of jQuery data cache data(name, value)_jquery

WBOY
Release: 2016-05-16 18:37:09
Original
988 people have browsed it

As a programmer, when you mention "caching", you can easily think of "client (browser cache)" and "server cache". The client cache is stored on the hard drive of the browser's computer, that is, the browser's temporary folder, while the server cache is stored in the server's memory. Of course, there are also dedicated cache servers in some advanced applications, and there are even implementations of caching using databases. Of course, these are beyond the scope of this article. What this article will discuss is the data caching implementation principle of jQuery, the most popular JavaScript framework. This is a new feature added since version 1.2.3 of jQuery.
1. The role of jQuery data cache
The role of jQuery data cache is described in the Chinese API as follows: "It is used to access data on an element and avoid the risk of circular references. ". How to understand this sentence? Take a look at my example below. I don’t know if it is appropriate. If you have a better example, please tell me.
(1) Examples with the risk of circular references (note the for in statement in the getDataByName(name) method):

Copy code The code is as follows:

Tom

Mike


(2) Examples of optimizing the risk of circular references (This example is actually similar to the jQuery cache implementation principle. The focus of this example is to rewrite the JSON structure of userInfo so that the name directly corresponds to the object key):
Copy code The code is as follows:

Tom

Mike


two , Simple implementation of jQuery setting data caching method
The implementation of jQuery data caching is actually very simple. Now I will implement the jQuery setting data caching method. I make the code as simple as possible, which will help you understand it easier. The implementation principle of data. The function and test code are as follows:
Copy code The code is as follows:

div1


div2

< script type="text/javascript">
//The cache object structure is like this {"uuid1":{"name1":value1,"name2":value2},"uuid2":{"name1":value1, "name2":value2}}, each uuid corresponds to an elem cache data. Each cache object can be composed of multiple name/value pairs, and value can be any data type. For example, it can be under elem like this Save a JSON fragment: $(elem).data('JSON':{"name":"Tom","age":23})
var cache = {};
//expando as elem New attributes are added. In order to prevent conflicts with user-defined ones, the variable suffix is ​​used here
var expando = 'jQuery' new Date().getTime();
var uuid = 0;
function data (elem, name, data)
{
//At least ensure that there are two parameters, elem and name, to obtain or set the cache
if (elem && name)
{
//Try to get the elem tag expando attribute
var id = elem[expando];
if (data)
{
//Set cache data
if (!id)
id = elem[expando] = uuid;
//If the id key object does not exist in the cache (that is, this elem has no data cache set up), first create an empty object
if (!cache[id])
cache[id] = {};
cache[id][name] = data;
}
else
{
//Get cache 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!


3. Precautions for using jQuery data cache
(1) Because the jQuery cache object is Globally, in AJAX applications, because the page is refreshed very rarely, this object will always exist. As you continue to operate the data, it is very likely that due to improper use, the object will continue to grow, ultimately affecting program performance. So we need to clean up this object in time. jQuery also provides the corresponding method: removeData(name), name is the name parameter you used when setting the data value.
In addition, based on my understanding of the jQuery code, I found that there is no need to manually clear the data cache in the following situations:
<1> Perform the remove() operation on elem, and jQuery will clear the possible cache of the object. jQuery related source code reference:
Copy code The code is 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> Perform empty() operation on elem, if the current elem child element exists Data cache, jQuery will also clear the data cache that may exist for child objects, because jQuery's empty() implementation actually calls remove() in a loop to delete child elements. jQuery related source code reference:
Copy code The code is 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 copy node clone() method will not copy the data cache. To be precise, jQuery will not allocate a new node in the global cache object to store the newly copied elem cache. jQuery replaces the possible cache pointing attributes (elem's expando attribute) with empty ones in clone(). If you copy this attribute directly, both the original and newly copied elem will point to a data cache, and the intermediate interoperation will affect the cache variables of the two elems. The following jQuery code deletes the expando attribute (jQuery 1.3.2, earlier versions did not handle it this way, obviously the performance of this method in the new version is better).
jQuery.clean([html.replace(/ jQueryd ="(?:d |null)"/g, "").replace(/^s*/, "")])[0];
Copying the data cache together is sometimes very useful. For example, in a drag operation, if we click on the source target elem node, a translucent elem copy will be copied to start dragging, and the data cache will be copied to the drag layer. , until the dragging is completed, we may get the information related to the currently dragged elem. Now the jQuery method does not provide us with such processing, what can we do? The first way is to rewrite the jQuery code. This method is obviously stupid and unscientific. The correct approach is to copy the data of the source target and reset the data to the copied elem, so that when the data(name, value) method is executed, jQuery will open up new space for us in the global cache object. The implementation code is as follows:
Copy code The code is as follows:

if (typeof($.data( currentElement)) == 'number')
{
var elemData = $.cache[$.data(currentElement)];
for (var k in elemData)
{
draggingDiv. 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 (i.e. uuid). Using this key, you can get the entire cache object, and then copy the object's data to the new object.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template