【问题标题】:Getting the list of polymer published properties获取聚合物已发布属性的列表
【发布时间】:2014-08-06 21:45:57
【问题描述】:

有没有办法获取聚合物组件中定义的所有published properties 的列表? (例如获取组件公共 API 的可用属性)

<polymer-element name="sample-component"
                 attributes="foo1 foo2" bar="10">
   /* ... */
</polymer-element>

<sample-component foo1="5"></sample-component>


document.querySellector('sample-component').attributes;
// returns bar and foo1 (which have a value assigned to them)
// but I want to get foo1 and foo2

【问题讨论】:

    标签: javascript polymer web-component


    【解决方案1】:

    最好使用element.publish 来获取元素的已发布属性列表。 (在聚合物 1.0 element.properties 中也是如此)。

    element.getAttribute('attributes) 不会包含在publish block 中设置的发布属性。

    【讨论】:

    • 聚合物 1.0 怎么样?已发布似乎不适用于聚合物 1.0 谢谢
    • 你试过element.properties吗?
    • 就是这样。这是我的第一个猜测,但由于某种原因,它在我第一次尝试时不起作用。编辑答案以包括聚合物 1.0。谢谢
    【解决方案2】:

    您可以通过element 属性访问元素定义(即polymer-element 本身)。所以

    document.querySelector('sample-component')
      .element.getAttribute('attributes')
    

    给你'foo1 foo2'(顺便说一句。在元素内你可以简单地写this.element。)

    请注意,这仅在 Polymer 注册并处理了所有元素后才有效,因此根据您要在何处使用此语句,您可能必须将其放入 polymer-ready 事件处理程序中:

    <script>
      addEventListener('polymer-ready', function() {
        console.log(document.querySelector('sample-component')
          .element.getAttribute('attributes'));
      });
    </script>
    

    更新:

    如果您想获取所有已发布属性的列表(即attributes 属性中的属性加上publish: {} 属性中的属性),您可以使用

       Object.keys(document.querySelector('sample-component').publish)
    

    给你['foo1', 'foo2']

    【讨论】:

    • 感谢@dirk-grappendorf。抱歉,我没有在我的问题中使用准确的术语。我用 Polymer 文档的链接编辑了问题。
    • 我相应地更新了我的答案。但埃里克更快;-)
    • 仅供参考,现在调用发布属性会为您提供一个具有键值对的对象,而不是问题中列出的数组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多