Encapsulation of deep objects

69 views
Skip to first unread message

Ian Spiro

unread,
Aug 22, 2014, 6:37:52 PM8/22/14
to polym...@googlegroups.com
I have the following Polymer element. On ready, I randomly assign a value to the random attribute then push this to the deep array. If in my demo.html, I instantiate three test-data objects, they will all have different values for random. But the deep array will be identical for all three. It contains the 3 randomly generated numbers, across the 3 instances.

Is this a bug? If I uncomment the line that reassigns deep to be an empty array, it works correctly. But for my purposes won't really work. I want to store a bunch of static data in an object but different instances should be allowed to modify that data without affecting each other. Is my only option to do an explicit deep-copy?


TEST-DATA.HTML

<polymer-element name="test-data" attributes="random deep">
  <template>
    <div>
      {{random}} / {{deep}}
    </div>
  </template>
  <script>

    Polymer('test-data', {
      random: null,
      ready: function() {
        this.random = Math.random();
        //this.deep = [];
        this.deep.push(this.random);
      },
      deep: [],
    });

  </script>

</polymer-element>


DEMO OUTPUT

3 `test-data` object:

0.11330667673610151 / 0.11330667673610151,0.5147093017585576,0.03896064590662718
0.5147093017585576 / 0.11330667673610151,0.5147093017585576,0.03896064590662718
0.03896064590662718 / 0.11330667673610151,0.5147093017585576,0.03896064590662718

Michael Bleigh

unread,
Aug 22, 2014, 6:43:24 PM8/22/14
to polym...@googlegroups.com
This happens because objects and arrays are passed by reference in JavaScript, not duplication. If you have properties that need to be initialized as arrays or objects, you should take care of it in the "created" lifecycle callback.

Reply all
Reply to author
Forward
0 new messages