【问题标题】:How to create a custom-element "resize" mixin for Polymer 2?如何为 Polymer 2 创建自定义元素“调整大小”mixin?
【发布时间】:2017-08-06 11:58:34
【问题描述】:

我正在尝试将 Polymer 1.8 组件升级到 Polymer 2。

正如文档中所解释的,behaviors 被类 mixin 替换,但我对这些并没有信心。经过一番搜索,关于如何替换iron-resizable-behavior,我无法找到如何构建它。

有人告诉我在哪里可以找到有关它的文档或/并解释我如何设计 mixin 以对事件做出反应?

谢谢

【问题讨论】:

    标签: ecmascript-6 polymer mixins web-component custom-element


    【解决方案1】:

    按照documentation,您只需要执行以下操作:

    变化:

    class MyElement extends Polymer.Element {
      // Implementation
    }
    

    收件人:

    class MyElement extends Polymer.IronResizableBehavior(Polymer.Element) {
      // Implementation
    }
    

    这对你有用吗?

    【讨论】:

    • 不,我试过了,但我有一个错误Polymer.IronResizableBehavior is not a function。当我查看行为代码时,它不是基于类的,正如 tony19 所说。
    • 那么您可能需要使用Polymer.mixinBehaviors,直到Polymer.IronResizableBehavior 未被重写为类行为。
    • 是的,这就是我所做的,现在正在运行。我错过了说行为是使用混合模式设计的那句话。谢谢
    【解决方案2】:

    混合行为

    2.0-preview branch of <iron-resizable-behavior> 中,Polymer.IronResizableBehavior 是一种混合行为(即,定义为对象而不是类混合)。 Polymer 2 提供Polymer.mixinBehaviors() 将一个或多个混合mixin 与一个类合并。

    用法:

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

    例子:

    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);
    

    行为类混合

    你可以像这样create a behavior-class mixin

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

    然后,您可以像这样在 Polymer 元素中使用它:

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

    混合行为+行为类混合

    您可以像这样一起使用混合行为行为类混合

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多