1

In Short:

In Polymer, I can't make this.$[id] work to query elements which have been dynamically generated, while this.shadowRoot.querySelector("#"+id) does the job without any problem. Why?

In Details

What I have:

  • A published array elements
  • Another array modifiedElements which contains data based on the first one
  • HTML blocks generated by repeat over the 2nd array

What I want:

  1. Update modifiedElements whenever elements is changed (✓)
  2. Update the HTML accordingly (✓)
  3. Query the new blocks (for some interactions) (not quite ✓)

My Polymer elements:

<polymer-element name="my-sorted-elements" attributes="elements">
    <template>
        <template repeat="{{el in modifiedElements}}">
            <div class="heading" on-click="{{toggle}}" target="collapse{{el.name}}">{{devices.name}}</div>
            <core-collapse id="collapse{{el.name}}">
                {{el.info}}
            </core-collapse>
        </template>
    </template>
</polymer-element>

... and its script:

Polymer('my-element', {

    ready: function() {
        this.modifiedElements = [];
        this.modifyElements();
    },

    elementsChanged: function() {
        this.modifyElements();
    },

    modifyElements: function() {
        for (var e in this.elements) {
            el = this.elements[e];
            // ... do stuff on el ...
            this.modifiedElements.push(el);
        }
    },

    toggle: function(event, detail, sender) {
        // This works:
        this.shadowRoot.querySelector("#"+sender.attributes['target'].value).toggle();
        // This doesn't (not found):
        this.$[sender.attributes['target'].value].toggle();
    }
})

Any idea why the second method doesn't work in toggle? Should I somehow update this.$, or is there a better way to do the whole thing?

benjaminplanche
  • 14,689
  • 5
  • 57
  • 69

1 Answers1

3

This is as designed. this.$['id'] is not supposed to work on dynamically added elements for example when they are inside <template repeate=...>, <template if=...> or added imperatively.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    Thanks for the quick reply and curating / My bad for not finding the other thread. Still kinda wondering about the best practice in such cases, but I will go for the "pro tip" of Scott Miles (http://stackoverflow.com/a/24589493/624547)... – benjaminplanche Apr 21 '15 at 15:23