How to implement Jquery.data ()

Source: Internet
Author: User

the role of Jquery.data () is to append (and retrieve) data to a normal object or DOM Element.

The following is a three-part analysis of how it is implemented:
1. Append data to the object with name and value, i.e. pass in three parameters, the first parameter is the object that needs additional data, the second parameter is the name of the data, and the third parameter is the value of the data. Of course, if you just get the value, you can not pass in the third argument.
2. Append the data to the object with another object, i.e. pass in two parameters, the first parameter is the data object that needs to be appended (we call "obj"), the second parameter is also an object (what we call "another"); the key-value pairs contained in "another" will be copied to "obj" Data cache (which we call "cache").
3. Append data to DOM element; Dom element is also an object, but IE6, IE7 has problems with garbage collection of objects directly attached to the DOM element, so we store this data in the global cache (What we call "GLOBALCAC He ")," Globalcache "contains the" cache "of multiple DOM element and adds a property on the DOM element to hold the corresponding UID of" cache ".

attaching data to an object with name and value


When attaching data to a normal object using Jquery.data (), it is essentially attaching a "cache" to the object and using a special property name.
The "cache" that holds the data is also an object, and the data that we append to "obj" actually becomes the "cache" property. and "Cache" is also a property of "obj", in JQuery 1.6, the name of this property is "JQUERY16" plus a random number (as mentioned below "jQuery16018518865841457738").

We can use the following code to test the functionality of Jquery.data ():

  1. <script type="Text/javascript" src="Jquery.js"></script>
  2. <script>
  3. obj = {};
  4. $.data (obj, ' name ', ' value ');
  5. document.write ("$.data (obj, ' name ') =" + $.data (obj, ' name ') + '<br /> ');
  6. for (var key in obj) {
  7. document.write ("obj." + key + '. Name = ' + Obj[key].name);
  8. }
  9. </Script>


The results shown are:

    1. $.data (obj, ' name ') = value
    2. Obj.jQuery16018518865841457738.name = Value


In this code, we first append an attribute to "obj" (named "Name", "value") and then get the appended data through $.data (obj, ' name '). In order to gain an insight into the implementation mechanism, we have used a loop to get the properties of "obj", in effect removing the "cache" object attached to "obj".

As you can see, jquery.data () actually attaches "obj" to an object named "jQuery16018518865841457738" (the name is random), that is, "cache". The property attached to an object in Jquery.data () is actually a property of the "cache".

We can implement a similar function with the following code:

  1. $ = function () {
  2. var expando = "JQuery" + ("1.6" + math.random ()). Replace (/\d/g, " );
  3. function GetData (cache, name) {
  4. return cache[name];
  5. }
  6. function SetData (cache, name, value) {
  7. Cache[name] = value;
  8. }
  9. function GetCache (obj) {
  10. Obj[expando] = Obj[expando] | | {};
  11. return Obj[expando];
  12. }
  13. return {
  14. Data: function (obj, name, value) {
  15. var cache = GetCache (obj);
  16. if (value = = = undefined) {
  17. return GetData (cache, name);
  18. } Else {
  19. SetData (cache, name, value);
  20. }
  21. }
  22. }
  23. }();



The first line of code in function defines "expando", or "jQuery1.6" Add a random number (0.xxxx) and remove the parts of the non-digital part; This format will be used elsewhere in jquery, not explored here; just know that this is a special name and can be used to identify different pages (such as "expando" in different iframe) will be different).

Next, you define the function GetData () that gets the data, which is to get a property from "cache", which in effect returns Cache[name].
The SetData () function is then used to set the "cache" property, which is actually the value of setting Cache[name].
This is followed by GetCache (), which gets the "cache" on "obj", i.e. Obj[expando], and if Obj[expando] is empty, it is initialized.
Finally, the data method is disclosed, the "cache" appended to "obj" is obtained based on the "obj", and the GetData () method is called when the two parameters are passed, and the SetData () method is called when the three parameters are passed.


attaching data to an object with another object


In addition to assigning values in the form of a name and value, we can also pass directly to another object ("another") as a parameter. In this case, the property names and property values of "another" are treated as multiple key-value pairs, and the "name" and "value" from which they are extracted are copied to the cache of the target object.

The functional test code is as follows:

  1. <script type="Text/javascript" src="Jquery.js"></script>
  2. <script>
  3. obj = {};
  4. $.data (obj, {name1: ' value1 ', name2: ' value2 '});
  5. document.write ("$.data (obj, ' name1 ') =" + $.data (obj, ' name1 ') + '<br /> ');
  6. document.write ("$.data (obj, ' name2 ') =" + $.data (obj, ' name2 ') + '<br /> ');
  7. for (var key in obj) {
  8. document.write ("obj." + key + '. name1 = ' + obj[key].name1 + '<br /> ');
  9. document.write ("obj." + key + '. name2 = ' + obj[key].name2);
  10. }
  11. </Script>



The results appear as follows:

    1. $.data (obj, ' name1 ') = value1
    2. $.data (obj, ' name2 ') = value2
    3. obj.jQuery1600233050178663064.name1 = value1
    4. obj.jQuery1600233050178663064.name2 = value2



In the above test code, we first pass in a "another" object with two key-value pairs, and then use $.data (obj, ' name1 ') and $.data (obj, ' name2 ') to get the additional data, and again, for a closer look at the mechanism, we traverse The "obj" method takes out the hidden "cache" object and obtains the value of the "Name1" property and the "Name2" property of the "Cache" object.

As you can see, jquery.data () actually attaches an object named "obj.jquery1600233050178663064" to "obj", which is "cache". Key-value pairs passed in Jquery.data () are copied to the "cache".

We can implement a similar function with the following code:

  1. $ = function () {
  2. //Other codes ...
  3. function Setdatawithobject (cache, another) {
  4. For (var name in another) {
  5. Cache[name] = Another[name];
  6. }
  7. }
  8. //Other codes ...
  9. return {
  10. Data: function (obj, name, value) {
  11. var cache = GetCache (obj);
  12. if (name instanceof Object) {
  13. Setdatawithobject (cache, name)
  14. } Else if (value = = = undefined) {
  15. return GetData (cache, name);
  16. } Else {
  17. SetData (cache, name, value);
  18. }
  19. }
  20. }
  21. }();



This code is modified on the basis of the previous code. The inner function setdatawithobject () is added first, and the implementation of this function is to traverse the properties of "another" and copy it to "cache".
Then, in the Open Data function, first determine the name of the second parameter passed in, and if this argument is an instance of type Object, call the Setdatawithobject () method.


attaching data to DOM Element


Because the DOM element is also an object, the previous method can also assign a value to the DOM element, but considering the garbage collection problem in IE6, IE7 (which does not effectively reclaim the attached object reference on the DOM element), jquery uses a common object that has no Append data in the same way.

The test code is as follows:

  1. <div id="div_test" />
  2. <script type="Text/javascript" src="Data.js"></script>
  3. <script>
  4. Window.onload = function () {
  5. div = document.getElementById (' div_test ');
  6. $.data (Div, ' name ', ' value ');
  7. document.write ($.data (Div, ' name '));
  8. }
  9. </Script>



The results appear as follows:

    1. Value



In the test code, a DOM element is obtained first through the document.getElementById method (or, of course, with the jQuery selector), and then a property is appended to the DOM element and then from the DOM element The additional attributes are removed and output.

Because there is a problem with IE6, IE7 garbage collection on the object reference on DOM element, we do not attach the object directly to the DOM element, but instead use the global cache and append a UID to the DOM element.

Here's how it's implemented:

  1. $ = function () {
  2. var expando = "JQuery" + ("1.6" + math.random ()). Replace (/\d/g, " );
  3. var globalcache = {};
  4. var uuid = 0;
  5. //Other codes ...
  6. function GetCache (obj) {
  7. if (obj.nodetype) {
  8. var id = obj[expando] = Obj[expando] | | ++uuid;
  9. Globalcache[id] = Globalcache[id] | | {};
  10. return Globalcache[id];
  11. } Else {
  12. Obj[expando] = Obj[expando] | | {};
  13. return Obj[expando];
  14. }
  15. }
  16. //Other codes ...
  17. }();



This code adds globalcache and UUID to the previous code, and modifies the GetCache () method.

The Globalcache object is used to hold the "cache" attached to the DOM Element and can be considered a "cache" container. The UUID represents the unique identifier for "cache" and is unique and self-growing. The UUID or is stored in the "expando" attribute of the DOM Element.
The GetCache () function adds a judgment that "obj" has a "nodeType" attribute, which is considered to be a DOM Element, in which case the ID appended to "obj", or Obj[expando], is first removed; if Obj[expan Do] is undefined, it is initialized with ++uuid, and after the ID is removed, the corresponding "cache", or Globalcache[id], is found in the Globalcache and returned.

At this point, the implementation of the Jquery.data () function is finished, but here's a question to consider: "Globalcache" Storage for Shbudu, and "cache" directly to a normal object? I think this should be a way of performance optimization, after all, less a reference to the level, the access speed should be slightly faster. This is a much-sought-after optimization in JQuery, with special handling in many of the others that could have been handled uniformly. But this to a certain extent, also caused the reading source of obstacles. This is, of course, the programming philosophy of the author (and other code contributors), and there is no comment.

How to implement Jquery.data ()

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.