Search code examples
javascriptpolymerweb-component

How to pass object literals as polymer attributes


In order to test some polymer custom elements of mine in isolation, I would like to be able to pass in js object literals for some attributes that would ordinarily come from parent elements. I'm having trouble figuring out how to do this. See this example code. If it were working as I would like it to, it would display a 1 and a 2 next to each other, but it doesn't work.

<script src="http://www.polymer-project.org/webcomponents.js"></script>
<link rel="import" href="http://www.polymer-project.org/components/polymer/polymer.html">

<polymer-element name="my-element" attributes="stuff">
  <template>
    {{stuff.one}} {{stuff.two}}
  </template>
  <script>
    Polymer('my-element', {
      ready: function () {
        console.log(this.stuff);
      }
    });
  </script>
</polymer-element>
<my-element stuff='{"one": 1, "two": 2}'></my-element>


Solution

  • Polymer only converts the JSON text into an object, if you initialize the stuff property with an empty hash:

    Polymer('my-element', {
        stuff: {},
        ready: function () {
            console.log(this.stuff);
        }
    });
    

    Without this, the stuff attribute is passed in as a string. The same goes for arrays.