Applying Behaviors with JS Mixins in Polymer 2

后端 未结 2 747
暗喜
暗喜 2020-12-30 12:51

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

2条回答
  •  孤城傲影
    2020-12-30 13:25

    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

        let Mixin = (superclass) => new MixinBuilder(superclass);
        class MixinBuilder {  
            constructor(superclass) {
              this.superclass = superclass;
            }
    
            with(...mixins) { 
             return mixins.reduce((c, mixin) => mixin(c), this.superclass);
            }
        }
    
        const MyMixin = subclass => class extends subclass {
          _test(){
    
          }
        }
    
        const MyMixinTwo = subclass => class extends subclass {
          _testTwo(){
    
          }
        }
    
        class MyElement extends Mixin(Polymer.Element).with(MyMixin,MyMixin2) {
           static get is() { 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.

提交回复
热议问题