Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

javascript - Polymer automatic node finding with dynamic id value

How can I access node that have dynamic id value using Polymer node finding by id?

For example

<template>
    <div id="{{ id }}"></div>
</template>

and in js

Polymer("my-element", {
    ready: function() {
        if (!this.id) {
            this.id = 'id' + (new Date()).getTime();
        }

        console.log(this.$.id); // this part needs to find my div element
    }
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's true that a JavaScript hash can be accessed using either dot . or array [] notation. If you have a literal name, you can use dot notation this.$.some_id. If you have an indirection, like this.id = 'some_id', then you can use array notation this.$[this.id] to find the same value.

The tricky part is that Polymer only populates $ array after first stamping the template, which happens before ready. If you had an external binding to this.id, this.$.[this.id] would work, but since you are setting this.id in ready it's too late for the $ convenience.

In this case, you can instead query your shadowRoot directly:

this.shadowRoot.querySelector('#' + this.id)

Pro tip: at some point a subclass may supply a new template, in which case this.shadowRoot will point to the new shadow-root and not the superclass version. For this reason, it's best to install a named div you can query against, e.g. this.$.id_div.querySelector('#' + this.id').


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...