子属性更改时重新评估对象绑定

时间:2015-11-29 01:18:31

标签: javascript html data-binding polymer

我正在尝试将数据提供程序包装在自定义元素中,以便在我的应用程序中使用中介模式,但是我对我遇到的这种行为感到有些困惑。

以下是我的数据提供商的缩短版本:

<dom-module id="archive-data">
  <script>
  (function () {
    //some helper functions 
    //...  
    var api = {
      is: 'archive-data',
      properties: {
        archive: {
          type: Object,
          value: { 
            name: value,
            ...,
            meetings: [] 
          },
          notify: true
        }
      },
      ready: function () { this.update(); },
      update: function () {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
          if (xhr.readyState == XMLHttpRequest.DONE) {
            var data = HELPERS.extractResult(xhr.response);
            this.archive.meetings = someFunction(data);
          }
        }.bind(this);
        xhr.open("POST", "serverAPI.cfc?method=getData");
        xhr.send();
      }
    };
    Polymer(api);
  }());
  </script>
</dom-module>

理念是这件事要异步请求来自后端的一些数据。稍后,如果应用程序对数据库进行了更改,则调解器可以在此提供程序上调用update(),并且在archive上具有绑定的任何元素都将获得更新。

因此调解员可以使用提供者:

<archive-data archive="{{archive}}"></archive-data> 
<other-element my-data="[[archive]]"></other-element>

我遇到的问题是数据绑定无法正常工作。我想知道为什么。据我所知,文档说它应该有效:

  

实现了聚合物中双向数据绑定和路径观察   使用与上述双向属性类似的策略   绑定:

     

当使用type: Object配置的属性的子属性时   更改时,元素会触发非冒泡的<property>-changed DOM事件   使用detail.path值指示对象上的路径   改变。

     

已注册对该对象感兴趣的元素(通过   然后,绑定或更改处理程序)可以采取适当的行动。

     

最后,这些元素会将通知转发给任何人   孩子们将对象束缚在一起,并且还会开火   <property>-changed事件,其中property是要通知的根对象   任何可能已将根对象绑定的主机。

我尝试了this.set('archive.meetings', someFunction(data));而不是直接分配,但这不起作用。

我也尝试在分配后直接运行this.fire('archive-changed');,但这也不起作用!

但是,如果我用新的archive对象替换整个this.archive = { meetings: someFunction(data) };对象,绑定将按预期重新计算。例如def fibLessThan(lim): ################# # Initial Setup # ################# fibArray=[1, 1, 2] i=3 ##################### # While loop begins # ##################### while True: tempNum = fibArray[i-2]+fibArray[i-1] if tempNum <= lim: fibArray.append(tempNum) i += 1 else: break print fibArray return fibArray limit = 4000000 fibList = fibLessThan(limit) ############# # summation # ############# evenNum = [x for x in fibList if x%2==0] evenSum = sum(evenNum) print "evensum=", evenSum

2 个答案:

答案 0 :(得分:2)

我认为有必要通知Polymer你的路径发生了变化,如下所示:

this.notifyPath('archive.meetings', this.archive.meetings);

以下是该官方documentation的完整示例:

<dom-module id="custom-element">
  <template>
    <div>{{user.manager.name}}</div>
  </template>

  <script>
    Polymer({
      is: 'custom-element',
      reassignManager: function(newManager) {
        this.user.manager = newManager;
        // Notification required for binding to update!
        this.notifyPath('user.manager', this.user.manager);
      }
    });
  </script>

</dom-module>

答案 1 :(得分:-1)

我看到了 this.set('user.manager', newManager); 有错误

  

未捕获的TypeError:this.set不是函数       在XMLHttpRequest.xhr.onreadystatechange