在聚合物2中使用JS Mixins的行为 [英] Applying Behaviors with JS Mixins in Polymer 2

查看:78
本文介绍了在聚合物2中使用JS Mixins的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要定义的自定义元素在聚合物2中具有Polymer.IronScrollTargetBehavior.

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

在聚合物1中,这可以通过将其添加到behaviors数组中来完成:

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

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

在Polymer 2 升级指南中,它说您应该:

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

将行为"作为返回类表达式的混入.

在链接的文章中,它说明了如何对混合包使用以下语法:

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) {  
    /* ... */
}

我基本上了解了这里发生的事情(尽管我发现mixin语法难以引起我的注意),并且我可以使示例代码正常工作.

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.

我无法做的就是将此概念应用于Polymer.IronScrollTargetBehavior,并为其创建一个mixin.由于该行为已经被定义为对象,因此我不知道该将其放置在什么地方.

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.

那么,在这种情况下如何实现适当的mixin,或者如果我走错了路,如何将已定义的Polymer行为之一应用于Polymer 2中的自定义元素?

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?

推荐答案

您可以通过扩展来将Polymer 2混合行为用作mixin Polymer.mixinBehaviors(behaviors, klass)其中
-behaviors是行为对象或行为数组
-klass是Element类.

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.

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

有关更多详细信息,请搜索Polymer源代码中的mixinBehaviors方法:polymer/lib/legacy/class.html

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

值得一读: https://www.polymer-project.org/2.0 /docs/upgrade#mixins

这篇关于在聚合物2中使用JS Mixins的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆