Search code examples
ecmascript-6polymermixinsweb-componentcustom-element

How to create a custom-element "resize" mixin for Polymer 2?


I'm trying to upgrade a Polymer 1.8 component to Polymer 2.

As explained in the documentation, behaviors are replaces by class mixin, but I'm not really confident with theses. After some search, about how to replace the iron-resizable-behavior, I'm not able to find how to build it.

Is there someone to show me where I can find some documentation on it or/and explain how can I design mixins to react on events?

Thanks


Solution

  • Hybrid Behavior

    In the 2.0-preview branch of <iron-resizable-behavior>, Polymer.IronResizableBehavior is a hybrid behavior (i.e., defined as an object instead of a class mixin). Polymer 2 provides Polymer.mixinBehaviors() to merge one or more hybrid mixins with a class.

    Usage:

    class NEW_CLASSNAME extends Polymer.mixinBehaviors(HYBRID_MIXINS_ARRAY, SUPERCLASSNAME) { ... }
    

    Example:

    class MyView1 extends Polymer.mixinBehaviors([Polymer.IronResizableBehavior], Polymer.Element) {
      static get is() { return 'my-view1'; }
    
      connectedCallback() {
        super.connectedCallback();
        this.addEventListener('iron-resize', this._logResizeEvent);
      }
    
      disconnectedCallback() {
        super.disconnectedCallback();
        this.removeEventListener('iron-resize', this._logResizeEvent);
      }
    
      _logResizeEvent(e) {
        console.debug('resize', e);
      }
    }
    
    window.customElements.define(MyView1.is, MyView1);
    

    Behavior-Class Mixin

    You could create a behavior-class mixin like this:

    const MyMixin = (superclass) => class extends superclass {  
      foo() {
        console.log('foo from MyMixin');
      }
    };
    

    Then, you'd use it in your Polymer element like this:

    class MyView1 extends MyMixin(Polmer.Element) {
      onClick() {
        this.foo(); // <-- from MyMixin
      }
    }
    

    Hybrid Behavior + Behavior-Class Mixin

    You could use hybrid behaviors and behavior-class mixins together like this:

    class MyView1 extends Polymer.mixinBehaviors([Polymer.IronResizableBehavior], MyMixin(Polmer.Element)) {
      onClick() {
        this.foo();                               // <-- from MyMixin
        console.log(this._interestedResizables);  // <-- from Polymer.IronResizableBehavior
      }
    }