【问题标题】:Polymer 1.0: <iron-meta> usagePolymer 1.0:<iron-meta> 用法
【发布时间】:2015-09-24 08:09:57
【问题描述】:

Polymer 1.0 元素&lt;iron-meta&gt; 的正确使用令人困惑。这是link on Github。这是Polymer demo site的链接。

有人可以提供一个正确的代码示例来说明如何使其工作吗?

这是我目前的代码。

<dom-module id="generic-element">
  <style>...</style>
  <template>
    <iron-meta id="meta" key="info" value="foo/bar"></iron-meta>
    The <code>value</code> stored at <code>key="info"</code> is <code><span>{{test}}</span></code>. 
  </template>
</dom-module>
<script>
  (function() {
    Polymer({
      is: 'generic-element',
      properties: {
        test: {
          value: function(){
            return "Hello world"; // This is the only thing I can get to work so far.
         // return (new Polymer.IronMetaQuery({key: 'info'}).value); // Doesn't totally break.
         // All my other below attempts totally fail. Everything breaks.
         // return this.$.meta.IronMetaQuery({key: 'info'}).value;
         // return this.IronMetaQuery({key: 'info'}).value;
         // return this.$.meta.byKey('info').getAttribute('value');
         // return this.$.meta.byKey('info').value;
          }
        }
      }
    });
  })();
</script>

这里是问题的Github link。这是一个Github repository,其中包含完整网络应用程序上下文中的完整问题代码。

【问题讨论】:

    标签: polymer web-component polymer-1.0 custom-element


    【解决方案1】:

    您的代码的问题是您试图将元素属性的默认值设置为在同一元素的模板中声明的值。在元素创建和元素附加之间发生的两件事包括 a) 设置了属性的默认值; b) 模板经过准备,以被压印到 DOM 中。这些任务是异步发生的,所以本质上你正在生成一个竞争条件。

    尝试在 ready() 回调中设置 test 默认值 - ready() 回调保证 DOM 已准备好被访问,在您的情况下,这正是您声明 &lt;iron-meta&gt; 键的位置。

    <dom-module id="generic-element">
      <style>...</style>
      <template>
        <iron-meta id="meta" key="info" value="foo/bar"></iron-meta>
        The <code>value</code> stored at <code>key="info"</code> is <code><span>{{test}}</span></code>. 
      </template>
    </dom-module>
    <script>
      (function() {
        Polymer({
          is: 'generic-element',
          properties: {
            test: String
          },
          ready: function () {
            // this will work
            this.test = this.$.meta.byKey("info");
          }
        });
      })();
    </script>
    

    jsbin:http://jsbin.com/vosekiwehu/edit?html,output

    【讨论】:

    • 谢谢。这有效,但您的代码中有错误。 this.$.test = this.$.meta.byKey("info"); 应该是:this.test = this.$.meta.byKey("info"); 但是您的总体想法有效。所以我会接受你的回答并投票。如果你有时间,你可能想为那些可能从中受益的追随者修改你的答案。
    • 哦,是的,很好。抱歉打错了。我已经纠正了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多