Search code examples
polymerweb-componentpolymer-1.0custom-element

Polymer 1.0: <iron-meta> usage


Proper usage of the Polymer 1.0 element <iron-meta> is confusing. Here is the link on Github. And here is the link to the Polymer demo site.

Can someone please provide a proper code example of how to make it work?

This is the code I have so far.

<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>

Here is the Github link to the issue. And here is a Github repository that contains the complete problem code in context of the complete web app.


Solution

  • The issue with your code is that you are trying to set your element property's default value to something that's declared inside that same element's template itself. Two of the things that happen between the time when the element is created and when that element is attached include a) properties' default values are set; and b) the template undergoes preparations to be stamped into DOM. These tasks happen asynchronously so in essence you are generating a race condition.

    Try setting your test default value inside the ready() callback - the ready() callback guarantees that DOM is ready to be accessed, which in your case is exactly where you declared your <iron-meta> key.

    <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