Analysis and simple implementation of jQuery data cache Function

Source: Internet
Author: User

For jQuery'sData Cache, I believe everyone will not be unfamiliar,JQuery Cache SystemNot only usedDOM Element,Animation and eventAnd so on. Therefore, in actual applications, we often need to cache some data for elements, which are often closely related to DOM elements. Because DOM elements (nodes) are also objects, we can directly extend the attributes of DOM elements. However, adding custom attributes and excessive data to DOM elements may causeMemory leakageSo we should try to avoid this. Therefore, a better solution is to use a low coupling method.

: For jQuery. data and jQuery. removeDataStatic Method, And based on the two methodsPrototype ExtensionYou can refer to the official API documentation.

JQuery provides a flexible and powerful caching method:

(1) first create a cache object in jQuery {}To save the cached data. Then extend an attribute with the value of expando to the DOM node to be cached.Here is"JQuery" + (new Date). getTime ().The expando value is equal to "jQuery" + current time. The element itself has very little possibility of this attribute, so you can ignore the conflict.

(2) set the value of each node as an auto-Increment Variable to maintain global uniqueness. The value of this id is used as the cache key to associate DOM nodes and data. That is to say, the cache [id] gets all the caches on this node, that is, the id is like the key to open a room (DOM node. And all the cache of each element is put into oneMap ingSo that multiple data can be cached at the same time.

(3) SoCache object structureIt should be like the following:

 cache ="uuid1": {         "name1""name2""uuid2": {         "name1""name2"};

, Each cache object can be composed of multipleName/value (name-value Pair) pairAnd the value can beAny data type.

 

Based on the above ideas, you can simply implement the functions of jQuery. data and jQuery. removeDate:

( cacheData = {},         win = window,         uuid = 0                expando = "cacheData" + (+ Date() + "").slice(-8         data =                  ( elem === "string"             (name !===                    }   ( elem === "object"             (!= elem[expando] = ++= cacheData[id] ===             (!= (value !==                thisCache[expando][name] =                 removeData =          ( elem === "string"        }   ( elem === "object"             (!             isEmptyObject =  (name   =                     =                                                    win.expando ===

Example:

HTML structure:

 

Js Code:

    var demo = document.getElementById("demo");        data(demo, "myName", "hcy");    console.log(data(demo, "myName")); // hcy    data(demo, "myBlog", "http://www.cnblogs.com/cyStyle");    console.log(data(demo, "myBlog")); // http://www.cnblogs.com/cyStyle        removeData(demo, "myBlog");    console.log(data(demo, "myBlog")); // undefined    console.log(data(demo, "myName")); // hcy    console.log(demo[expando]); // 1        removeData(demo);    console.log(demo[expando]); // undefined};

Result of the example in firefox:

For the simple jQuery cache system implemented in the above example:Add a random attribute expando to the DOM element, which is used to store the id value of the access cache data. Just like the DOM element has a key to enable the cache safe, with the key, you can enable the cache safe at any time. The data originally stored in the DOM element is transferred to the cache, And the DOM element itself only needs to store a simple attribute, in this way, we can minimize the risk caused by DOM elements.

 

Finally, some terms or explanations may be biased. I hope you can correct your shoes and give some suggestions. In addition, theoretically, the data and removeData methods can be used for caching any object.Local object or window object, Will existMemory leakage and loop referenceAnd Other Issues (^_^ from the Internet), so it is generally suitable for DOM nodes, you can also combineEvents and animationsCache data on DOM nodes.

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.