具有动态id值的聚合物自动节点查找 [英] Polymer automatic node finding with dynamic id value

查看:109
本文介绍了具有动态id值的聚合物自动节点查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过ID使用Polymer节点查找来访问具有动态id值的节点?

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

例如

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

和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
    }
});


推荐答案

确实可以使用任一方式访问JavaScript哈希点或数组 [] 表示法。如果您有文字名称,则可以使用点符号 this。$。some_id 。如果你有间接,比如 this.id ='some_id',那么你可以使用数组表示法这个。$ [this.id] 找到相同的值。

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.

棘手的部分是Polymer只填充 $ 数组后首先标记模板,该模板发生在 ready 之前。如果你有一个外部绑定到 this.id 这个。$。[this.id] 可行,但是因为你在准备中设置 this.id ,对于 $ 方便。

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.

在这种情况下,您可以直接查询您的shadowRoot:

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

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

专业提示:某些子类可能提供一个新模板,在这种情况下, this.shadowRoot 将指向新的shadow-root而不是超类版本。出于这个原因,最好安装一个可以查询的命名div,例如 this。$。id_div.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').

这篇关于具有动态id值的聚合物自动节点查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆