Polymer, how to pass value to paper-date-picker attribute that expects string?

混江龙づ霸主 提交于 2019-12-24 03:35:17

问题


I'm trying to use paper-date-picker inside my element. How to pass value to paper-date-picker's 'date' attribute?

<!-- This is working: -->
<paper-date-picker date="2000/1/21"></paper-date-picker>


 <!-- This is NOT working: 
 Inside <my-birthdate birthdate="1977/1/2"></my-birthdate> -->
<paper-date-picker date='{{birthdate}}'></paper-date-picker>

Here is the Plunk.


回答1:


After looking at the source for the date-picker, it doesn't handle text very well. Basically, you have to add an observer that converts the value into a date. Also, remove the birthdate from the picker. Here's a quick example...

<polymer-element name="my-birthdate" attributes="birthdate">
    <template>
        birthdate = {{birthdate}}
        <paper-date-picker id="picker"></paper-date-picker>
    </template>
    <script>
        Polymer("my-birthdate", {
            birthdateChanged: function (oldValue, newValue) {
                if (newValue)
                    this.$.picker.date = new Date(newValue);
            }
        });
    </script>
</polymer-element>

Keep in mind, I am not error checking the new value... you'll have to do that.




回答2:


Values in attributes are always strings. If you want Polymer to convert an attribute string to another type, you have to hint the type you want.

<my-birthdate birthdate="1977/1/2"></my-birthdate>

We want birthdate to be a Date. If we change the definition like so:

<script>
  Polymer({
    birthdate: new Date()
  });
</script>

then Polymer knows to convert 1977/1/2 into a Date object.

http://plnkr.co/edit/ftbtl0eCrklAuIbxKRiP?p=preview

Keep in mind that the binding here is different from above:

<paper-date-picker date='{{birthdate}}'></paper-date-picker>

In this case we are asking Polymer to bind paper-date-picker.date property directly to the birthdate property. We do not go through attributes, because then we would have to convert to string and back and it's dramatically slower.

There is no support in paper-date-picker to make a Date out of a String value in birthdate. Therefore, when working with paper-date-picker directly (not via attributes) birthdate must be Date valued.



来源:https://stackoverflow.com/questions/28325014/polymer-how-to-pass-value-to-paper-date-picker-attribute-that-expects-string

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