作为How to extend multiple elements with Polymer和Polymer multiple inheritence/composition的后续工作,基于他们的回答,我想知道是否有可能在多个Web组件(和多个导入)之间共享mixin以重用功能。
Mixins似乎是跨多个自定义元素共享功能的唯一方法。但是,似乎您只能在一个导入中使用mixin。这意味着,如果您有一个mixin,它为Web组件提供了特定的功能(例如draggable
),并且如果不在同一导入中,则无法将其混入Polymer元素的构造中。
也许我那里出了点问题,但是如果不是,那感觉就像使用mixins也不是很灵活,因为我仍然无法跨Web组件共享功能。
更新:
正如Scott Miles在其注释中指出的,可以在多个导入中使用mixins的。我只是不确定如何做到这一点,事实证明,这非常简单。
假设我们有一个mixin,应该在多个组件之间共享,但是组件分布在许多导入中。所有要做的就是在window
对象上的自己的导入中定义该mixin。因此,例如:
shared.html
<script>
window.sharedMixin = {
// shared functionality goes here
};
</script>
然后,在另一个导入中的另一个组件中重用该mixin就像导入
shared.html
一样简单。my-component.html
<link rel="import" href="path/to/shared.html">
从那时起,
sharedMixin
可以用作该导入中的全局对象:Polymer('my-component', Platform.mixin({
// my-component logic
}, sharedMixin);
希望对别人有帮助。我将撰写有关此内容的博客文章,并将其链接到此处。
更新2
我在这里写了一篇博客文章:http://pascalprecht.github.io/2014/07/14/inheritance-and-composition-with-polymer/
最佳答案
建议使用类似全局的组件。
制作一个<name-you-like>
并使用get/set进行更改(虽然它们只是悲伤的字符串,但您也可以使用属性)。
从Polymer API guide中,您将看到类似这样的有效(好看)示例:
<polymer-element name="app-globals">
<script>
(function() {
// these variables are shared by all instances of app-globals
var firstName = 'John';
var lastName = 'Smith';
Polymer({
ready: function() {
// copy global values into instance properties
this.firstName = firstName;
this.lastName = lastName;
}
});
})();
</script>
</polymer-element>
并使用javascript es5 getters/setter与他们一起玩,例如在上述情况下,
<polymer-element name="app-globals">
<script>
(function() {
// these variables are shared by all instances of app-globals
var firstName = 'Arnold';
var lastName = 'Schwarzenegger';
Polymer({
ready: function() {
// copy global values into instance properties
this.firstName = firstName;
this.lastName = lastName;
},
get fullTerminatorName() {
return this.firstName + ' ' + this.lastName;
}
});
})();
</script>
</polymer-element>
I'll be back.
关于polymer - 是否可以在Polymer中跨Web组件(和导入)共享mixin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24180622/