Home Web Front-end JS Tutorial Detailed explanation and implementation of jQuery data cache data(name, value)_jquery

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

May 16, 2016 pm 06:37 PM
jquery Data cache

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.
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

Introduction to how to add new rows to a table using jQuery Introduction to how to add new rows to a table using jQuery Feb 29, 2024 am 08:12 AM

jQuery is a popular JavaScript library widely used in web development. During web development, it is often necessary to dynamically add new rows to tables through JavaScript. This article will introduce how to use jQuery to add new rows to a table, and provide specific code examples. First, we need to introduce the jQuery library into the HTML page. The jQuery library can be introduced in the tag through the following code:

See all articles