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