Kristjan Liiva
Kristjan Liiva

Reputation: 9549

Polymer 1.0 element property object binding, maintain structure

I want to create a custom element that takes a JSON object as input.

<activity-tracker activity='{"title": "Lord Meowser", "description": "lala"}'></activity-tracker>

The element itself looks like this

<dom-module id="activity-tracker">
   <style>
     :host {
       display: block;
       box-sizing: border-box;
     }
   </style>

   <template>
     <p>{{activity}}</p>
     <p>{{activity.title}}</p>
   </template>

 </dom-module>

And the property binding

properties: {
  activity: {
     title: {
        type:String,
        value: '...'
     },
     description:{
        type:String,
        value: '...'
     }
   }
},

<p>{{activity}}</p> results in {"title": "Lord Meowser", "description": "lala"}

<p>{{activity.title}}</p> is empty

How can I map it? And how should I handle if user inserts something else, lets say activity="notanobject". Currently, defined internal object is just overwritten and the string is shown.

Upvotes: 0

Views: 235

Answers (1)

Flavio Ochoa
Flavio Ochoa

Reputation: 961

    <dom-module id="activity-tracker">
    <style>
     :host {
       display: block;
       box-sizing: border-box;
     }
    </style>

   <template>
     <p>{{variable}}</p><!-- this shows [object Object]-->
     <p>{{variable.title}}</p> <!-- this shows Lord Meowser-->
     <p>{{variable.description}}</p> <!-- this shows lalala-->
   </template>

    <script>
      Polymer({
        is:"activity-tracker",
        properties:{
          variable:{
            type:Object,
            value: function(){return {};}
          }
        }

      });
    </script>  

</dom-module> 

<activity-tracker variable='{"title": "Lord Meowser", "description": "lala"}'></activity-tracker>

This should work.

Upvotes: 1

Related Questions