如何观察聚合物中的子属性变化?

时间:2016-12-10 09:10:18

标签: javascript polymer polymer-1.0 observers

对于这个对象:

obj = {
        a:'a value',
        b:'b value'
      }

每当ab的值发生变化时,我都需要调用一个函数。 我看到Observe changes for an object in Polymer JS,但该解决方案对我不起作用。

我尝试添加像这样的观察者是不成功的:

 observers: [
    'abc(obj.*)' //abc is function which need to be called
 ]

 observe: {
    'obj.a': 'abc'     // here I'm observing a's attribute
 },

Plunker: http://plnkr.co/edit/BvX25wJHJh7i2aeyVBks?p=preview

1 个答案:

答案 0 :(得分:2)

在您的Plunker中,在obj.a回调中ready()更改后未调用观察者,因为子属性是直接分配的,它不会自动触发观察者(或数据)的更改事件绑定)看。这是更正后的plunker

Polymer docs描述了如何observe subproperty changes

  

为了让Polymer正确检测子属性更改,必须使用以下两种方法之一更新子属性:

     

还有第三种方式:通过拨打notifyPath

this.obj.a进行更改后,您可以通过调用this.notifyPath('obj.a', this.obj.a)通知观察者并更新绑定:

this.obj.a = 100;
this.obj.a++;
this.notifyPath('obj.a', this.obj.a);



HTMLImports.whenReady(() => {
  Polymer({
    is: 'x-foo',
    properties: {
      obj: {
        type: Object,
        value: () => ({a: 1, b: 2})
      }
    },
    observers: [
      '_objChanged(obj.a, obj.b)'
    ],
    _objChanged: function(a, b) {
      console.log('a', a, 'b', b);
    },
    _doNotifyPath: function() {
      this.obj.a++;
      this.obj.b++;
      this.notifyPath('obj.a', this.obj.a);
      this.notifyPath('obj.b', this.obj.b);
    }
  });
});

<head>
  <base href="https://polygit.org/polymer+1.11.3/components/">
  <script src="webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="polymer/polymer.html">
</head>
<body>
  <x-foo></x-foo>

  <dom-module id="x-foo">
    <template>
      <div>obj.a = [[obj.a]]</div>
      <div>obj.b = [[obj.b]]</div>
      <button on-tap="_doNotifyPath">Notify Path</button>
    </template>
  </dom-module>
</body>
&#13;
&#13;
&#13;

或者,您可以将设置和通知与this.set('obj.a', 'new value')

结合使用
this.set('obj.a', this.obj.a + 1);

&#13;
&#13;
HTMLImports.whenReady(() => {
  Polymer({
    is: 'x-foo',
    properties: {
      obj: {
        type: Object,
        value: () => ({a: 1, b: 2})
      }
    },
    observers: [
      '_objChanged(obj.a, obj.b)'
    ],
    _objChanged: function(a, b) {
      console.log('a', a, 'b', b);
    },
    _doSet: function() {
      this.set('obj.a', this.obj.a + 1);
      this.set('obj.b', this.obj.b + 1);
    }
  });
});
&#13;
<head>
  <base href="https://polygit.org/polymer+1.11.3/components/">
  <script src="webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="polymer/polymer.html">
</head>
<body>
  <x-foo></x-foo>

  <dom-module id="x-foo">
    <template>
      <div>obj.a = [[obj.a]]</div>
      <div>obj.b = [[obj.b]]</div>
      <button on-tap="_doSet">Set</button>
    </template>
  </dom-module>
</body>
&#13;
&#13;
&#13;

codepen