13

If storing multiple (10+) values on a large number of divs, is it more optimal to store them all in a single object, or as separate values?

Single Object:

$("#div_id").data("data", {foo:1, bar:2});

Separate Values:

$("#div_id")
  .data("foo", 1)
  .data("bar", 2);

What are the trade-offs of each method? Some of these attributes will be accessed frequently (during event callbacks like dragging, for instance).

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Luke Dennis
  • 14,212
  • 17
  • 56
  • 69

3 Answers3

13

In 1.4 you can do this:

$('#somediv').data({ one : 1, two : 2, three : 3 });

This is a great way to initialize the data object. HOWEVER, in 1.4.2, bear in mind that using this form will REPLACE ANY existing data on this element. So, if you try this:

$('#somediv').data( 'one', 1 );

$('#somediv').data({ two : 2, three : 3 });

You will be blowing away the value for 'one'.

(On a personal note, I think it is a shame since jQuery already makes extensive use of merging objects with its $.extend. Its not clear to me why that wasn't used here.)

UPDATE (suggested by user: @ricka, thank you):

1.4.3 and on, it merges the data (http://api.jquery.com/data/#data-obj):

In jQuery 1.4.3 setting an element's data object with .data(obj) extends the data previously stored with that element. jQuery itself uses the .data() method to save information under the names 'events' and 'handle', and also reserves any data name starting with an underscore ('_') for internal use.

Prior to jQuery 1.4.3 (starting in jQuery 1.4) the .data() method completely replaced all data, instead of just extending the data object. If you are using third-party plugins it may not be advisable to completely replace the element's data object, since plugins may have also set data.

mkoistinen
  • 7,724
  • 3
  • 41
  • 56
  • I love this solution. Clean and easy – Fabrizio Sabato Dec 17 '14 at 14:52
  • odd - using `src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js` with `nodeElements = nodeGroup.selectAll('circle') .data(nodes, function (node) { return node.id }) .data(links, function (link) { return link.source })` results in the data still being over written. – Elysiumplain Feb 16 '18 at 18:22
6

If both approaches are as easy to use in your code, go for storing a single object. It avoids the extra overhead of calling the data() method every time you need a value. This way, you can fetch the mapping object with one call to data(), and then retrieve values from this object as many times as you want without having to call data() again.

The data() method uses objects to map elements to keys/values under the hood, so it does not offer any performance improvements over managing a mapping object yourself.

Ayman Hourieh
  • 132,184
  • 23
  • 144
  • 116
3

I'd probably do something like:

var data = $("#div_id").data();   
data.foo=1;  
data.bar=2;
Jethro Larson
  • 2,337
  • 1
  • 24
  • 24