Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying Behaviors with JS Mixins in Polymer 2

I want a custom element I'm defining to have the Polymer.IronScrollTargetBehavior in Polymer 2.

In Polymer 1, this can be done by adding it to the behaviors array:

Polymer({
    is: 'my-element',
    behaviors: [Polymer.IronScrollTargetBehavior]
});

In the Polymer 2 upgrade guide, it says that you should:

Implement "behaviors" as mixins that return class expressions.

In the linked article, it explains how you can use the following syntax for mixins:

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

class MyClass extends MyMixin(MyBaseClass) {  
    /* ... */
}

I mostly get what's going on here (although I find the mixin syntax difficult to wrap my mind around), and I can get sample code to work.

What I haven't been able to do is apply this concept to Polymer.IronScrollTargetBehavior, and create a mixin for it. Since that behavior is already defined as an object, I don't know where to fit it in.

So, how do I implement the proper mixin in this scenario, or if I'm on the wrong path, how to I apply one of the defined Polymer behaviors to my custom element in Polymer 2?

like image 215
emarcee Avatar asked Jan 24 '17 21:01

emarcee


Video Answer


1 Answers

You can use the Polymer 2 hybrid behaviours as mixins by extending Polymer.mixinBehaviors(behaviors, klass) where
- behaviors is the Behavior object or array of behaviors
- klass is the Element class.

i.e.

<dom-module id="element-name">
  <template><!-- ... --></template>
  <script>
    class MyElement extends Polymer.mixinBehaviors([MyBehavior, MyBehavior2], Polymer.Element) {
     static get is() { return 'element-name' }
     /* ... */
    }
    customElements.define('element-name', MyElement);
  </script>
</dom-module>

For more detailed information search the Polymer source code for mixinBehaviors method: polymer/lib/legacy/class.html

worth reading: https://www.polymer-project.org/2.0/docs/upgrade#mixins

like image 183
magiccrafter Avatar answered Sep 22 '22 15:09

magiccrafter