如何在不重新定义属性的情况下观察聚合物中的继承属性



如何在不重新定义属性的情况下在聚合物中观察到继承的属性?例如,假设一个名为 InheritedBehaviour 的行为模块具有一个名为 x 的属性,并按如下方式添加到自定义模块中:

<dom-module id="foo-bar">
    <script>
        Polymer({
            is: 'foo-bar',
            behaviors: [
                InheritedBehaviour
            ]
        });
    </script>
</dom-module>

可以通过以下方式观察此属性:

<dom-module id="foo-bar">
    <script>
        Polymer({
            is: 'foo-bar',
            behaviors: [
                InheritedBehaviour
            ],
            properties: {
                x: {
                    type: Number,
                    observer: '_doSomething'
                }
            },
            _doSomething: function() {
                console.log('Something!');
            }
        });
    </script>
</dom-module>

但是,这会"重新定义"此对象的属性。因此,如果InheritedBehaviour x设置为具有reflectToAttribute: true,这将不再在重新定义时设置(除非它全部重写在新对象上(。

如何扩展而不是覆盖继承的属性?

谢谢

您可以使用复杂的观察器(通过 Polymer 对象定义中的 observers 数组(来观察行为的属性:

Polymer({
  is: 'x-foo',
  behaviors: [InheritedBehavior],
  observers: ['_doSomething(foo)'],
  _doSomething: function(foo) {...}
});

HTMLImports.whenReady(() => {
  let MyBehavior = {
    properties: {
      foo: {
        type: String,
        value: 'hi',
        reflectToAttribute: true
      }
    }
  };
  
  Polymer({
    is: 'x-foo',
    behaviors: [MyBehavior],
    observers: ['_fooChanged(foo)'],
    _fooChanged: function(foo) {
      console.log('foo', foo);
    },
    _changeFoo: function() {
      const x = ['hey there', 'hello'];
      this.foo = this.foo === x[0] ? x[1] : x[0];
    }
  });
});
<head>
  <base href="https://polygit.org/polymer+1.7.0/components/">
  <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
  <link rel="import" href="polymer/polymer.html">
</head>
<body>
  <x-foo></x-foo>
  <dom-module id="x-foo">
    <template>
      <div>{{foo}}</div>
      <button on-tap="_changeFoo">Change foo</button>
    </template>
  </dom-module>
</body>

代码笔

另一种选择是在行为本身中实现观察器,然后覆盖它,如下所示:

在继承行为中

properties: {
    x: {
        type: Number,
        observer: '_doSomething'
    }
},
doSomething: function() {
    console.log('Designed to be overridden!');
}

在 foo-bar 中:

doSomething: function() {
    // Here you can do whatever you want to do!
    // This method overrides the one in the behaviour
}

我删除了下划线,因为此方法将不再是"私有"的。

最新更新