I'm trying to wrap my head around how computed observables / properties in Polymer 2 work and should be used. I've created a repro analogous to my real code that zooms in on the thing I'd like to see reviewed: my use of computed
properties in a Polymer 2 component.
Some things that might be helpful while reviewing:
- I've explicitly left out CSS and styling because I want to focus on getting the code right.
- We're targeting modern browsers, specifically for IE only Edge.
The main thing I'm worried about is hasSelectedPerson
and its underlying "private" function. For one thing, it feels weird that I have to ask for a person
as an argument, when it's also available as a property on the class.
<link rel="import" href="//polygit.org/polymer+:master/components/paper-button/paper-button.html">
<dom-module id="people-template">
<template>
<template is="dom-repeat" items="[[people]]" as="person">
<paper-button raised on-click="_onSelectClick" item="[[person]]">
[[person.name]]
</paper-button>
</template>
<template is="dom-if" if="[[hasSelectedPerson]]">
<p>Selected: [[selectedPerson.id]] [[selectedPerson.name]]</p>
</template>
</template>
<script>
class PeopleTemplate extends Polymer.Element {
static get is() {
return "people-template";
}
static get properties() {
return {
people: {
type: Array,
value: [
{ id: 1, name: "John Doe" },
{ id: 2, name: "Mary Havenstein" },
{ id: 3, name: "Janie van Staffelen" },
]
},
selectedPerson: Object,
hasSelectedPerson: {
type: Boolean,
computed: "_hasSelectedPerson(selectedPerson)"
}
}
}
_onSelectClick(event) {
this.set("selectedPerson", event.composedPath()[0].item);
}
_hasSelectedPerson(person) {
return !!person;
}
}
customElements.define(PeopleTemplate.is, PeopleTemplate);
</script>
</dom-module>
You can also check it on plnkr.co where it's wrapped in a plain index file to see it actually running.
So, to summarize:
- Any specific comments on my use of
computed
? - Any generic comments on this component?