Polymer: FlattenedNodesObserver Strange Behavior

Created on 16 Jan 2018  路  4Comments  路  Source: Polymer/polymer

Description

It hard to describe this issue, as I do not really understand it. so I will just provide an example with the expected result.

Element

The element will just observer new nodes and add it to an array

class TestinbgElement extends Polymer.Element {
      static get is() { return 'testinbg-element'; }
      static get properties() {
        return {
          items: {
            type: Array,
            value: []
          }
        };
      }

      connectedCallback() {
        super.connectedCallback();
        this.__observer = new Polymer.FlattenedNodesObserver(this.$.slot, (info) => {
          this._processNewNodes(info.addedNodes);
        });
      }

      disconnectedCallback() {
        super.disconnectedCallback();
        this.__observer.disconnect();
      }

      _processNewNodes(nodes) {

        nodes.forEach((node) => {
          if(node.nodeType === Node.ELEMENT_NODE) {
            this.push('items',node);
          }
        });

        console.log(this.items);
      }
    }

Usage

 <testinbg-element>
       <div>I am content 1</div>
        <div>I am content 2</div>
  </testinbg-element>

<testinbg-element>
     <div>I am content 3</div>
      <div>I am content 4</div>
</testinbg-element>

Expected result

Array >> (2) [div, div] // for the first element instance
Array >> (2) [div, div] // for the second element instance

Actual Result

Array >> (2) [div, div] // for the first element instance
Array >> (4) [div, div , div , div] // for the second element instance

Live Repository

https://github.com/hyyan/strange-behavior-FlattenedNodesObserver~~
http://jsbin.com/jurozobuja/edit?html,console,output

Browsers Affected

  • [x] Firefox
  • [x] Chrome
  • [x] IE 11
  • [x] Edge

Versions

  • Polymer: v2.3.1
  • webcomponents: v1.0.22

Most helpful comment

You need to change line 35 to value: () => {return []} so each instance gets its own array. Its easy to overlook in the docs.

All 4 comments

JSBin that shows the issue: http://jsbin.com/jurozobuja/edit?html,console,output

Thanks @TimvdLippe I was just preparing one :)

You need to change line 35 to value: () => {return []} so each instance gets its own array. Its easy to overlook in the docs.

@morbidick That's great , thanks , this will solve the problem

Was this page helpful?
0 / 5 - 0 ratings