具有双向绑定属性的Polymer自定义元素

时间:2017-07-14 18:27:35

标签: javascript polymer

我有一个Polymer-element来显示和设置一个评级(1-5星),我无法让它工作,因为它显示给定的评级值,并传播回值,即,如果点击其中一颗星,则更改{{item.rating}}。可能是什么问题?

我使用这样的元素,它不会改变item.rating

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

使用纸张输入,它可以工作:

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

元素本身就在这里:

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

1 个答案:

答案 0 :(得分:1)

您的rating属性未正确声明。您已声明了两个属性:ratingnotify,但您可能需要在notify: true属性上设置rating

改变这个:

properties: {
  rating: String,
  notify: true
}

到此:

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

请参阅demo