【问题标题】:Polymer: how to bind an element's property to a promise result?聚合物:如何将元素的属性绑定到承诺结果?
【发布时间】:2017-02-16 04:11:10
【问题描述】:

假设我有这个元素:

<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 回调?

【问题讨论】:

    标签: data-binding promise polymer polymer-1.0


    【解决方案1】:

    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>
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 2017-02-13
    相关资源
    最近更新 更多