0

somehow getting jquery data() function return an object by ref.

it is a way in javascript to point to the object him self without to modify the ref object ?

here is my demonstration of the problem :

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var  c= console.log ;
$(document).ready(function(e) {
    var _data   = $("#elem").data();
    var _xdata = _data ; // should be a miror object 
    console.log($("#elem").data() );
    _xdata.id = "changes applied back to #elem.data object !!!"  ;
    console.log($("#elem").data() );
    //any way to separate between $("#elem").data() and _xdata ??
}) ;
</script>
<div id="elem" data-id="1" data-foo="some data"></div> 
foxdanni
  • 199
  • 1
  • 19

3 Answers3

2

This isn't a jQuery issue - its a javascript one. When you're assigning _xdata to _data, you're actually assigning the value of the reference to the _data object (a touch confusing I know). If you'd like to create a "mirror object", you should clone it like:

var _xdata = jQuery.extend(true, {}, _data);

EDIT: I'm always too slow here, but if you're looking for a shallow copy you could go with:

var _xdata = jQuery.extend({}, _data);
urban_raccoons
  • 3,499
  • 1
  • 22
  • 33
  • this is not javascript issue its jquery try without cloning the object just getting the object not by reference : // should be a cloned object \n var _data = $("#elem").data(); \n _data.id = "changes applied back to #elem.data object !!!" ;\n console.log($("#elem").data() ); – foxdanni May 07 '13 at 21:10
  • Well if you'd like to manipulate the _data variable, you can make a copy of it (not the whole element, just the object you're getting retuned from data() ) and then you'll be fine. – urban_raccoons May 07 '13 at 21:16
  • anyway this solved my problem `var _data = jQuery.extend({},$("#elem").data());` – foxdanni May 07 '13 at 21:16
0

You can use jQuery's .clone() method to clone the object (and it's data), instead of creating a reference as you're doing now.

var _xdata = $("#elem").clone(true).data();

That way you can manipulate the cloned data without affecting the original.

musicinmyhead
  • 1,466
  • 9
  • 11
  • true ! but clone will clone the element itself and in my project it mean to clone a very large element (with a lot of sub elements , events etc) sorry .. this is not optimized solution for me – foxdanni May 07 '13 at 21:07
0

Another thing is, values from data-whatever are stored in internal cache upon page load. So when you write $("#something").data("whatever") it returns value from the time page was loaded regardless of the data-whatever value written in html in that specific moment.

Goran Lepur
  • 594
  • 1
  • 4
  • 15