


Detailed explanation and implementation of jQuery data cache data(name, value)_jquery
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):
(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):
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:
//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:
Perform the remove() operation on elem, and jQuery will clear the possible cache of the object. jQuery related source code reference:
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);
}
}
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:
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:
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.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version
God-level code editing software (SublimeText3)