-1

I have an Object that describes my document. Each document contains layers, that described in Objects in an array

var example = {
    id: 'some_id',
    layers: [{
        id: 'some_layer_id',
        width: 100,
        height: 200
    }]
};

There are different types of layers, each has it's template:

var layer_templates = [{
    type: 'text',
    width: 100,
    height: 100,
    style: 'common'
}];

I create new layers in jQuery event:

jQuery('#button').on('click', function () {
    var ldata = layer_templates[0]; // get a template
    ldata['id'] = 's-l-' + Math.random().toString(); // create an id
    example['layers'].push(ldata); // add new "layer" to document
    console.log(example['layers']); // check
});

Every time i add new ldata layer to example['layers'] array, it keeps only initial object with id: 'some_layer_id'and rewrites all newly created objects with the last one.

Please check jsFiddle:Problem in action

AlexNasonov
  • 587
  • 1
  • 9
  • 21

1 Answers1

1

The problem is that you are not duplicating your template. You are using and re-using the SAME template among all your layers

var ldata = layer_templates[0];
ldata['id'] = 's-l-' + Math.random().toString(); // create an id

in actuality, ldata is just a pointer that is referencing the template, adding the id value to it only modifies your template so it looks like this now:

var layer_templates = [{
    type: 'text',
    width: 100,
    height: 100,
    style: 'common',
    id: 's-l-0.08636776800267398'
}];

NEXT time you try to add ANOTHER layer, you do the same thing yet again, which only pulls and changes the template once again... in the end, EVERY layer references the same template and therefore is the exact same data.

To fix this, you need to COPY your template, one way to do this is using JSON:

var ldata = JSON.parse(JSON.stringify(layer_templates[0]));

This method creates an entirely new ldata object that is a copy of the template.

Lochemage
  • 3,974
  • 11
  • 11