Polymer 1.0 element property object binding, maintain structure

空扰寡人 提交于 2019-12-12 03:45:36

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/32008029/polymer-1-0-element-property-object-binding-maintain-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!