0

Disclaimer: This is slightly mind-boggling, it's been a long night and I'm not a native speaker - so pls. forgive if the description is unclear. Pls. just comment and I'll try to clarify :)

I am trying to make a Datatables-table editable, and so far it looks quite good. But I got a surprise when I looked at the results in detail and it turned out that my little function to clone a row also modified the original row!

for a repro, pls. have a look at the saved page which I stored @ http://mbaas.de/edperm.html. Open the console, click on the "speichern"-Button: this will just log the data to the console. (Just to make sure the values are what we expect). Now click on the small icon to the left of the "7" in the last row: this is supposed to clone that row (JS-Function cloneRow which I'll show later) and watch the console-output: check the array that is printed immediately after "cloneRow!" - as you see in the code, nothing has been done to update data, yet data[3][0] has been changed already! And, BTW, line3 should be totally unaffected anyway by this update - I want to read that row, change the id and append it.

So, here is the code of cloneRow:

function cloneRow(arg)
{
    var oTable = $("#tabPerm").DataTable();
    console.log('cloneRow!');
    var d1a = oTable.data();
    console.log(d1a);
    arg=$(arg).closest('tr');
    var d = oTable.row(arg).data();
    console.log("Vor Zuweisung d");
    var d2a = oTable.data();
    console.log(d2a);

    d[0]=-7;
    console.log("Nach Zuweisung d");
    var d3a = oTable.data();
    console.log(d3a);
    oTable.row.add(d).draw();
    var d4a = oTable.data();
    console.log(d4a);
}

What is the explanation of this effect? Is it timing of console-output or what...?

MBaas
  • 7,248
  • 6
  • 44
  • 61
  • 1
    http://stackoverflow.com/questions/7389069/console-log-object-at-current-state – adeneo Oct 22 '15 at 05:35
  • Thank you - that sounds very plausible. BUT I have now update cloneRow to assign different (distinct) variables for every logging - and still that line3 is shown modified right at the start of cloneRow. (variable `d1a`) – MBaas Oct 22 '15 at 05:56
  • 1
    @MBaas: It doesn't matter that you're using different variable names. It matters that `oTable.data();` returns the same object every time. – Bergi Oct 22 '15 at 06:11
  • @Bergi But oTable is not supposed to return the same object every time - this data is being changed with the row.add-statement. – MBaas Oct 22 '15 at 06:19
  • 1
    @MBaas: Yes, the object is changed (mutated, its properties are changed), but I'm pretty sure it's still the same object. And at least, you can try `data[3] == d && d == data[2]` (or whatever row you selected). Notice that you *did not clone it* - it's still the same row, appearing twice in the table. – Bergi Oct 22 '15 at 06:25
  • Ok, finally I got it. I was not aware of this behaviour when assigning object. Thanks for explaning! – MBaas Oct 22 '15 at 07:34

0 Answers0