简体   繁体   中英

Polymer custom element with two-way binding of attribute

I have a Polymer-element to display and set a rating (1-5 stars), and I do not manage to make it work in the sense that it displays a given rating value, and propagates back the value, that is, changing {{item.rating}} in case of clicking on one of the stars. What could be the problem ?

I use the element like this, which does not change item.rating :

<yp-rating rating="{{item.rating}}"></yp-rating>

Using a paper-input, it works:

<paper-input value="{{item.rating}}" label="Rating"></paper-input>

The element itself is here:

<dom-module id="yp-rating">
    <template>
        <style is="custom-style">
        iron-icon {
            --iron-icon-fill-color: lightgray;
        }
        </style>

        <iron-icon th:title="#{rating1}" icon="{{star(rating, 1)}}" on-tap="setStar" data-s="1"></iron-icon>
        <iron-icon th:title="#{rating2}" icon="{{star(rating, 2)}}" on-tap="setStar" data-s="2"></iron-icon>
        <iron-icon th:title="#{rating3}" icon="{{star(rating, 3)}}" on-tap="setStar" data-s="3"></iron-icon>
        <iron-icon th:title="#{rating4}" icon="{{star(rating, 4)}}" on-tap="setStar" data-s="4"></iron-icon>
        <iron-icon th:title="#{rating5}" icon="{{star(rating, 5)}}" on-tap="setStar" data-s="5"></iron-icon>

    </template>
    <script type="text/javascript">
        Polymer({
            is : "yp-rating",
            properties: {
                rating: String,
                notify: true
                //readOnly: false,
                //reflectToAttribute: true
            },
            star: function(r, l) {
                return (this.rating && this.rating >= l) ? "star" : "star-border";
            },
            setStar: function(e) {
                this.rating = e.target.getAttribute("data-s");
                console.log("Rating set to " + this.rating);
                e.stopPropagation();
            }
        });
    </script>
</dom-module>

Your rating property is not declared correctly. You've declared two properties: rating and notify , but you probably meant to set notify: true on the rating property.

Change this:

properties: {
  rating: String,
  notify: true
}

to this:

properties: {
  rating: {
    type: String,
    notify: true
  }
}

See demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM