NicolasR
NicolasR

Reputation: 2312

Using Polymers own behaviors in Polymer 2.x

I am experimenting with Polymer 2.x and what I don't understand is how to use Polymers own behaviors in Polymer 2.x, iron-resizable-behavior as an example.

The Polymer 2.0 upgrade guide tells us that for our own components we should work with class expression mixins. That's fine but what about Polymers own behaviors? Are they in the progress of being rewritten as mixins or will they remain unchanged? There is a Polymer.mixinBehaviors method that seems to allow me to use Polymer 1.x mixins. Is this the final solution or is this an intermediate step?

To phrase it another way: are the Polymer behaviors considered Polymer 2.x although we are told to use mixins for our own components?

Sources:

https://www.polymer-project.org/2.0/docs/upgrade#upgrading-to-class-based-elements

Applying Behaviors with JS Mixins in Polymer 2

Upvotes: 8

Views: 3826

Answers (3)

Niklas
Niklas

Reputation: 1299

So I found a way how to use the iron-resizable-behavior in Polymer2
Instead of using the Mixin I am making use of the syntax of codeMonkey and extended his answer to show how to use it
As far as I know, this solution is a hybrid for Polymer 1 & 2

class customElement extends Polymer.mixinBehaviors([Polymer.IronResizableBehavior], Polymer.Element) {
    static get is() { return 'custom-element'; }

    ready() {
        super.ready();

        this.addEventListener('iron-resize', () => { this.onWidthChange() });

    }

    onWidthChange() {
        var w = this.offsetWidth;
        if (w > 0)
            console.log("Width of page is now ", w);
    }

}

Upvotes: 2

Eko Putra Pratama
Eko Putra Pratama

Reputation: 377

I think Polymer has an API for that. I think it is dedupingMixin. Below is an example how to create a mixin for your own behavior and how to use it in your element class.

var MyBehaviorMixin = Polymer.dedupingMixin(function(superClass){
  return class MyBehavior extends superClass {
    constructor() {
      super();
    }

    methodInBehavior() {
      return "this method is defined in Behavior";
    }
  }
}
class MyElement extends MyBehaviorMixin(Polymer.Element){
  constructor(){
    super();
    console.log(this.methodInBehavior());
  }
}

Upvotes: 6

codeMonkey
codeMonkey

Reputation: 4815

class MyElement extends Polymer.mixinBehaviors([Polymer.IronFormElementBehavior], Polymer.Element) { ... }

Upvotes: 10

Related Questions