views:

341

answers:

3

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).

+2  A: 

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
A: 

I'd probably do something like:

var data = $("#div_id").data();   
data.foo=1;  
data.bar=2;
Jethro Larson
A: 

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.)

mkoistinen