1

I have a DataTables plugin defined as

var oTable = $('#table1').dataTable({
      'aaData': data,
      'aoColumns': columns,
      'bScrollInfinite': true,
      'bScrollCollapse': true,
      'iDisplayLength': 20,
      'sScrollY': '300px'
});

var oTable_Copy = oTable.slice();

Now whenever any value in oTable changes, the corresponding value also changes in oTable_Copy. How do I prevent oTable_Copy from changing?

Valentin Mercier
  • 5,256
  • 3
  • 26
  • 50
user544079
  • 16,109
  • 42
  • 115
  • 171
  • 5
    You would have to do a clone... all you're doing is copying references. – Brad Jul 28 '14 at 17:19
  • 2
    Create a clone of `$('#table1')` first and call `dataTable` again. Or maybe you can clone `oTable`, but I don't know how `dataTable` works internally, so creating a clone of the DOM element and just applying the plugin again might be the safer way. – Felix Kling Jul 28 '14 at 17:20
  • 1
    Why not just create another element and do `$('#table1, #table2').dataTable(obj)` or something similar, what do you expect to achieve by this ? – adeneo Jul 28 '14 at 17:21
  • possible duplicate of [What is the most efficient way to clone an object?](http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-an-object) – php_nub_qq Jul 28 '14 at 17:23
  • I'm a bit surprised that you accepted the given answer. `oTable` is a jQuery object containing DOM elements. Converting to and from JSON doesn't work in this case. Why did you accept the answer? – Felix Kling Jul 28 '14 at 19:14

1 Answers1

0

the easiest way (assuming no loops) would be

var yourDeepCopyObj = JSON.parse(JSON.stringify(oTable));
dannyde
  • 122
  • 4
  • This doesn't work with DOM elements, which is what the OP is using here. I'm really surprised this answer was accepted. – Felix Kling Jul 28 '14 at 19:14
  • as i said - assuming no loops. you can try .extend(true, source, dest) http://api.jquery.com/jquery.extend/ – dannyde Jul 28 '14 at 19:22
  • But there are loops in this case. And possible event handlers and other state. Converting to and from JSON is not a solution for this problem. There is no point in making assumptions that can't be fulfilled anyway. *edit:* `$.extend` is not useful for cloning DOM elements either. – Felix Kling Jul 28 '14 at 19:24