【问题标题】:Data-binding with child's child element in Polymer与 Polymer 中子元素的数据绑定
【发布时间】:2017-04-19 01:45:46
【问题描述】:

我使用 Skygear 作为 BaaS。 我创建了一个聚合物元素skygear-app(就像polymerfire 一样)来初始化skygear 实例。

  <skygear-app name="skygear" app={{skygear}} end-
  point="https://xyz.skygeario.com/" api-key="SECRET"></skygear-app>

我也可以通过

成功登录
  passwordSignIn: function(){
    skygear.loginWithEmail(this.email, this.password).then(
      function(){
        console.log('login ok');
        console.log(skygear.currentUser.id);
        this.currentUser = skygear.currentUser;
      }
    );

我可以通过console.log(skygear.currentUser.id); 获得userId,但是, 我无法使用数据绑定 {{skygear.currentUser.id}} 获取 userId。

  <h4>Access Token: [[skygear.accessToken]]</h4> <!-- working -->
  <h4>User Id: [[skygear.currentUser.id]]</h4> <!-- not working -->

{{skygear.endpoint}} 等 1 级属性有效; 但是像 {{skygear.currentUser.id}} 这样的 2 级属性不会。

数据绑定是否仅限于 1 级?有什么想法可以解决吗?

【问题讨论】:

    标签: data-binding polymer polymer-1.0 skygear


    【解决方案1】:

    根据polymer1.0 doc,二级属性为Unobservable changes,参考:https://www.polymer-project.org/1.0/docs/devguide/data-system#unobservable-changes

    我们可以使用skygear容器提供的onUserChanged来通知聚合物app。

    这是最小的 Polymer skygear-app

      Polymer({
        is: 'skygear-app',
          apiKey: {
            type: String
          },
          endPoint: {
            type: String
          },
          app: {
            type: Object,
            notify: true,
            computed: '__computeApp(name, apiKey, endPoint)'
          }
        },
        __computeApp: function(name, apiKey, endPoint) {
          if (apiKey && endPoint) {
            skygear.onUserChanged(() => {
              this.notifyPath('app.currentUser.id');
            });
            skygear.config({
              apiKey: apiKey,
              endPoint: endPoint
            }).then(() => {
              this.notifyPath('app.currentUser.id');
            });
            return skygear
          } else {
            return null;
          }
    
          return skygear
        }
      });
    

    【讨论】:

    • .then() 里面的匿名函数中的this 不是正确的this。 XD
    • 我们不必在配置后通知。他们应该是独立的。
    • 我认为应该有2个notifyPath。首先是 onUserChanged(),它在用户登录、注销或更改电子邮件时更新值。其次是在 config()/init() 上,获取当前登录的用户。 (而this 的范围不是您代码中的预期范围)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    • 2018-07-02
    相关资源
    最近更新 更多