Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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>classMyElementextendsPolymer.mixinBehaviors([MyBehavior, MyBehavior2], Polymer.Element) {
     staticgetis() { 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

Solution 2:

Polymer 2.0 has a compatibility layer that still supports the old Polymer function syntax. Most of the 2.0 preview elements, if not all, still retain the old syntax. The breaking changes are mostly in the dom-module markup.

If you are composing new elements, it is recommended you switch over to the class based syntax. If however you are porting 1.0 elements to 2.0 and those elements rely on Polymer behaviors, I don't think you much choice at this juncture but to retain the old syntax.

In the class-based syntax you can fluently simulate Element multiple inheritance of class mixins with something like this

letMixin = (superclass) => newMixinBuilder(superclass);
    classMixinBuilder {  
        constructor(superclass) {
          this.superclass = superclass;
        }

        with(...mixins) { 
         return mixins.reduce((c, mixin) =>mixin(c), this.superclass);
        }
    }

    constMyMixin = subclass => classextends subclass {
      _test(){

      }
    }

    constMyMixinTwo = subclass => classextends subclass {
      _testTwo(){

      }
    }

    classMyElementextendsMixin(Polymer.Element).with(MyMixin,MyMixin2) {
       staticgetis() { return'my-element' }
    }  

You can separate the MixinBuilder into its own file and then reference it as an Html Import dependency whenever composing elements that use mixins.

Post a Comment for "Applying Behaviors With Js Mixins In Polymer 2"