Polymer:如何将元素的属性绑定到promise数据?

时间:2017-02-15 16:09:05

标签: data-binding promise polymer polymer-1.0

假设我有这个元素:

<dom-module id="my-element">
  <template>
    <auth-service is-authorized="{{isAuthorized}}"></auth-service>
  </template>

  <script>
    Polymer({
      is: 'my-element',

      properties: {
        isAuthorized: {
          type: Boolean,
          value: false
        }
      },

      ready: function () {
       if (this.isAuthorized) doStuff()
       else dontDoStuff()
      }
    })
  </script>
</dom-module>

这个孩子的auth-service元素:

<dom-module id="auth-service">
  <script>
    Polymer({
      is: 'auth-service',

      properties: {
        isAuthorized: {
          type: Boolean,
          value: false
        }
      },

      ready: function () {
        var self = this
        self.fetchAuthorization()
          .then(function () {
            self.set('isAuthorized', true)
          })
          .catch(function () {
            self.set('isAuthorized', false)
          })
      },

      fetchAuthorization: function () {
        //I know this is silly, but it's for the sake of the example
        if (!localStorage.authorization) return Promise.reject('Unauthorized')
        return Promise.resolve(JSON.parse(localStorage.authorization))
      }
    })
  </script>
</dom-module>

只有在auth-service的ready回调中的'fetchAuthorization'承诺得到解决后,我才能确保只调用my-element的ready回调?

1 个答案:

答案 0 :(得分:0)

observer添加到isAuthorized属性。

<dom-module id="my-element">
  <template>
    <auth-service is-authorized="{{isAuthorized}}"></auth-service>
  </template>

  <script>
    Polymer({
      is: 'my-element',

      properties: {
        isAuthorized: {
          type: Boolean,
          value: false,
          observer: '_authorizationChanged'
        }
      },

      _authorizationChanged: function () {
       if (this.isAuthorized) doStuff()
       else dontDoStuff()
      }
    })
  </script>
</dom-module>