Polymer v2.0: how to write reusable mixin code

Lets say I want to write set of mixins. As I understand it, each mixin should provide some piece of functionality and don't affect or rely any other mixins (except when it extends another mixin directly).

So i write something like this:

const MixinA = superClass => class extends superClass {
  connectedCallback() {
    this.addEventListener('click', this.handleClick_);
  }

  /**
   * @return {Array.<string>}
   */
  static get observers() {
    return [
      'handleMyPropChange_(myProp)',
    ];
  }
}

Then I add something like this:

const MixinB = superClass => class extends superClass {
  /**
   * @return {Array.<string>}
   */
  static get observers() {
    return [
      'handleMyPropChange_(myProp)',
    ];
  }
}

If i apply both of this mixins to same element, then one of handleMyPropChange_ will be hidden and second will be triggered two times.

Same problem is possible with and handleClick_ in this example.

There were no such problem with Polymer v1 behaviors.

The only way i've found is to add some mixin specific prefix to each private class member to give them unique names, but it looks not very handyю What is the best option to handle this problem?


In Polymer 2, you are extending a class. This means that only there can only be one function of any given name. You are basically overriding the previously defined function with the latest. The function is firing twice because each mixin is registering an observer, these don't de-dupe.

If the function is the same logically, I would abstract it out. If they are different logically I would provide different more clear names based on what the function is doing.

链接地址: http://www.djcxy.com/p/5340.html

上一篇: 聚合物应用刷新策略

下一篇: Polymer v2.0:如何编写可重用的mixin代码