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

Source: Internet
Author: User

As a programmer, when talking about "cache", you can easily think of "client (browser cache)" and "server cache ". The client cache is stored on the hard disk of the viewer's computer, that is, the temporary folder of the browser, and the server cache is stored in the server memory. Of course, there are dedicated cache servers in some advanced applications, the database is even used for caching. Of course, these are not covered in this article. This article will discuss the data cache implementation principle of jQuery, the most popular JavaScript framework. This is a new feature that jQuery1.2.3 has introduced.
I. Functions of jQuery data cache
The function of jQuery data cache is described in the Chinese API as follows: "It is used to access data on an element to avoid the risk of circular reference ". How can I understand this sentence? Let's look at the examples below. I don't know if it is appropriate. If you have a better example, let me know.
(1) Examples of cyclic reference risks (note the for in statement in the getDataByName (name) method ):
Copy codeThe Code is 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) Example of optimizing the risk of circular reference (this example is similar to the jQuery cache implementation principle. The focus of this example is to rewrite the JSON structure of userInfo so that the name and object key are directly matched):
Copy codeThe Code is 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>

Ii. Simple implementation of jQuery's data cache setting method
The implementation of jQuery data cache is actually very simple. Next I will implement jQuery to set the data cache method. I will make the code as simple as possible, which helps you better understand the implementation principles of data. The function and test code is as follows:
Copy codeThe Code is as follows:
<Div id = "div1"> div1 </div> <br/>
<Div id = "div2"> div2 </div>
<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, value can be of any data type. For example, you can store a JSON clip $ (elem) in elem ). data ('json': {"name": "Tom", "age": 23 })
Var cache = {};
// Expando is a newly added attribute of elem. To prevent conflicts with user-defined attributes, a variable suffix is used here.
Var expando = 'jquery '+ new Date (). getTime ();
Var uuid = 0;
Function data (elem, name, data)
{
// At least two elem and name parameters are required for cache fetch or cache setting.
If (elem & name)
{
// Try to get the expando attribute of the elem label
Var id = elem [expando];
If (data)
{
// Set cache data
If (! Id)
Id = elem [expando] = ++ uuid;
// If the id key object in the cache does not exist (that is, this elem has not set the data cache), create an empty object first.
If (! Cache [id])
Cache [id] = {};
Cache [id] [name] = data;
}
Else
{
// Obtain 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!
</Script>

Iii. Considerations for using jQuery data cache
(1) Because jQuery cached objects are global, this object will always exist in AJAX applications due to few page refreshes. As you continue to operate data, it is very likely that this object will become larger due to improper use and ultimately affect program performance. Therefore, we need to clear 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 jQuery code, I found that you do not need to manually clear the data cache in the following situations:
<1> after you perform the remove () operation on elem, jQuery clears the cache that may exist in the object. JQuery source code reference:
Copy codeThe 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 the empty () operation on elem. If the current elem sub-element has a data cache, jQuery also clears the data cache that may exist in the sub-object, because jQuery empty () the implementation is to call remove () cyclically to delete sub-elements. JQuery source code reference:
Copy codeThe 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 clone () method of the jQuery replication node does not copy the data cache. Specifically, jQuery does not allocate a new node in the global cache object to store the new replication elem cache. In clone (), jQuery replaces the possible cache pointing attribute (expando attribute of elem) with null. If you directly copy this attribute, it will lead to both the original and new elem pointing to a data cache, and the intermediate interoperability will affect the cache variables of the two elem. The following jQuery code deletes the expando attribute (jQuery1.3.2. This is not the case for earlier versions. It is clear that the new version provides better performance ).
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 the source target elem node to copy a translucent elem copy and start dragging, and copy the data cache to the drag layer. When the drag ends, we may obtain the information about the currently dragged elem. Currently, the jQuery method does not provide us with such a processing method. The first method is to rewrite jQuery code. This method is obviously silly and unscientific. The correct method is to copy the data from the source object and reset the data to the elem. In this way, 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 codeThe Code is 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. If there is only one elem parameter, this method returns its cache key (uuid ), you can use this key to obtain the entire cached object, and then copy the data of the object to the new object.

Related Article

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.