Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 562
cayblood Avatar asked Nov 14 '14 01:11

cayblood


People also ask

What supports both upward and downward data flow?

Double-curly brackets ( } ) support both upward and downward data flow.

Which form of data binding allows upward and downward data flow in polymer JS?

Automatic bindings allow upward and downward data flow.


2 Answers

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.

like image 189
Dirk Grappendorf Avatar answered Oct 02 '22 20:10

Dirk Grappendorf


Another way to do it:

myElem.html

<link rel="import"
      href="http://www.polymer-project.org/1.0/samples/components/polymer/polymer.html">

<dom-module id="my-element">
    <template>
        <div> {{stuff.one}} {{stuff.two}} </div>
    </template>

    <script>
      Polymer({
          is: "my-element",
          properties: {
              stuff:{
                  type: Object,
                  value: {"one":"default_1","two":"default_2"}
              }
          }
      });
    </script>
</dom-module>

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="http://www.polymer-project.org/1.0/samples/components/webcomponentsjs/webcomponents-lite.js"></script>
    <link rel="import" href="myElem.html">
  </head>
  <body>
    <my-element></my-element>
    <my-element stuff={"one":"1","two":"2"}></my-element>
  </body>
</html>

Result

default_1 default_2  
1 2
like image 35
TLJ Avatar answered Oct 02 '22 18:10

TLJ