Realization of jquery data caching function

Source: Internet
Author: User
Tags current time extend uuid delete cache

Objective
For jquery data caching, I believe that everyone is not unfamiliar, the jquery caching system is not only used in DOM elements, animation, events, etc. are useful to this caching system. So in peacetime applications, we often need to cache some of the elements of the data, and this data is often closely related to the DOM elements. Because DOM elements (nodes) are also objects, we can extend the properties of DOM elements directly, but if you add custom attributes and too much data to a DOM element that can cause a memory leak, you should try to avoid doing so. A better solution, therefore, is to use a low coupling method to connect the DOM to the cached data.

Also: for Jquery.data and Jquery.removedata static methods, and for the introduction and usage of the prototype extension methods based on these two methods, you can view the official API documentation.

Realize the idea
jquery provides a set of flexible and powerful caching methods:
(1) First create a cache object {} inside jquery to hold the cached data. Then extend a property with a value of expando on the DOM node that needs to be cached, this is "jQuery" + (new Date). GetTime (). Note: The value of expando equals "jQuery" + current time, the element itself has very little likelihood of this attribute, so you can ignore the conflict.
(2) Then the value of each node's Dom[expando] is set to a self increasing variable ID, which remains globally unique. The value of this ID is used as the cache key to correlate the DOM node and the data. That is, Cache[id] takes all the caches on this node, that is, the ID is like a key to open a room (DOM node). All the caches of each element are placed in a map map so that multiple data can be cached at the same time.
(3) So the cache object structure should look like the following:

copy code code as follows:


var cache = {


"Uuid1": {//DOM node 1 caching data, "UUID1" equals Dom1[expando]


"name1": value1,


"name2": value2


},


"Uuid2": {//DOM node 2 caching data, "Uuid2" equals Dom2[expando]


"name1": value1,


"name2": value2


}


// ......


};


Each UUID corresponds to a elem cached data, and each cached object can be composed of multiple name/value (name-value pairs), and value can be of any data type.

Simple simulation implementation
Based on the above ideas, you can simply implement the Jquery.data and Jquery.removedate functions:

copy code code as follows:


(function (window, undefined) {


var cachedata = {},//object used to store data


win = window,//cache window to a variable


uuid = 0,


//Declaration random number (8-bit)


//Note that the random number generated by the +new Date () is of type A, and the slice method can be used only after an empty string is concatenated (or transformed using the ToString method) into a string.


expando = "CacheData" + (+new Date () + ""). Slice (-8);


//(+new Date ()). ToString (). Slice (-8) is equivalent to expando


//write Cache


var data = function (elem, name, value) {


//or using native method to validate string Object.prototype.toString.call (elem) = = = "[Object String]"


//If Elem is a string


if (typeof Elem = = "string") {


//If the name parameter is passed in, the write cache is


if (name!== undefined) {


Cachedata[elem] = name;


}


//Return cached data


return Cachedata[elem];


//If Elem is a DOM node


} else if (typeof Elem = = "Object") {


var id,


Thiscache;


//If the expando property is not present in Elem, add a expando property (first to set the cache for the element), otherwise get the existing expando and ID values directly


if (!elem[expando]) {


id = elem[expando] = ++uuid;


Thiscache = Cachedata[id] = {};


} else {


id = Elem[expando];


Thiscache = Cachedata[id];


}


//A random number is used as an attribute of the current cached object, and the cached object can be found by using the random number


if (!thiscache[expando]) {


Thiscache[expando] = {};


}


if (value!== undefined) {


//data is stored in the cached object


Thiscache[expando][name] = value;


}


//Returns data stored by DOM elements


return thiscache[expando][name];


}


};


//Delete cache


var removedata = function (elem, name) {


//If Elem is a string, delete the property value directly


if (typeof Elem = = "string") {


Delete Cachedata[elem];


//If key is a DOM node


} else if (typeof Elem = = "Object") {


//If the expando property is not present in Elem, execution is terminated without deleting the cache


if (!elem[expando]) {


return;


}


//detects if the object is empty


var isemptyobject = function (obj) {


var name;


for (name in obj) {


return false;


}


return true;


}


removeattr = function () {


try {


//IE8 means that standard browsers can use delete directly to remove attributes


Delete Elem[expando];


} catch (e) {


//Ie6/ie7 Use the RemoveAttribute method to remove a property


Elem.removeattribute (expando);


}


},


id = Elem[expando];


if (name) {


//Delete only the specified data


Delete Cachedata[id][expando][name];


//If the object is empty, the data object corresponding to the ID is deleted


if (Isemptyobject (Cachedata[id][expando)) {


Delete Cachedata[id];


removeattr ();


}


} else {


//Remove all data that the DOM element is saved to the cache


Delete Cachedata[id];


removeattr ();


}


}


};


//The data and Removedata are hung under the window global object, so that both functions can be accessed externally


Win.expando = expando;


win.data = data;


win.removedata = Removedata;


}) (window, undefined);


Example:
HTML structure:

Copy code code as follows:


<div id= "demo" style= "height:100px; width:100px; Background: #ccc; Color: #fff; margin:20px; Text-align:center; line-height:100px; " >


Demo


</div>


JS Code:

copy code code as follows:


window.onload = function () {


//Test


var demo = document.getElementById ("demo");


//write Cache


Data (demo, "MyName", "homocysteine");


Console.log (Data (demo, "MyName")); Homocysteine


Data (demo, "MyBlog", "Http://www.cnblogs.com/cyStyle");


Console.log (Data (demo, "MyBlog")); Http://www.cnblogs.com/cyStyle


//Delete a cache value for a DOM element


Removedata (demo, "MyBlog");


Console.log (Data (demo, "MyBlog")); Undefined


Console.log (Data (demo, "MyName")); Homocysteine


Console.log (Demo[expando]); 1


//delete DOM element


Removedata (demo);


Console.log (Demo[expando]); Undefined


};


Firefox Example results screenshot:

For the above example, a simple caching system for jquery: First add a randomly generated attribute expando to the DOM element, which holds the ID value of accessing the cached data, just as the DOM element has a key to the cache safe, which can be opened at any time with a key. The data that was originally stored in the DOM element is transferred to the cache, the DOM element itself simply stores a simple attribute, so that the risk of a memory leak caused by a DOM element (what the situation does not know, as everyone says ~) can be avoided to the minimum.

Conclusion
Confused and finally, there are some terms or explanations may be biased, look at the children's shoes and give some suggestions; In addition, the data and Removedata methods can be used in any object cache, in theory, but if applied to local objects or window objects, there is a memory leak, Issues such as circular references (^_^ seen from the web), so it is generally appropriate for DOM nodes, and can also combine events and animations to cache data for DOM nodes. Ps:cache is really important! Need to understand slowly ~
Because sharing, so simple, because of sharing, so happy.

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.