2014-06-12 32 views
9

作爲對How to extend multiple elements with PolymerPolymer multiple inheritence/composition的跟進,根據他們的回答,我想知道是否可以在多個Web組件(和多個導入)中共享混合以重用功能。是否有可能在Polymer中跨Web組件(和導入)共享混合?

Mixins似乎是跨多個自定義元素共享功能的唯一方法。但是,似乎只能在一次導入中使用混入。也就是說,如果你有一個mixin,它爲web組件提供了一個特定的功能(比如draggable),如果它不在同一個導入中,就不可能將它混合到你的Polymer元素的構造中。

也許我在那兒弄錯了一些問題,但如果不是這樣,感覺使用mixins也不是很靈活,因爲我仍然無法跨Web組件共享功能。

UPDATE:

正如Scott萬里在他的評論中指出,這是可能在多個導入使用混入。我只是不知道該怎麼做,事實證明,這是非常簡單的。

假設我們有一個應該在多個組件之間共享的mixin,但組件分佈在很多導入中。所有人必須做的是在window對象上定義該mixin自己的導入。因此,例如:

shared.html

<script> 
    window.sharedMixin = { 
    // shared functionality goes here 
    }; 
</script> 

,然後重複使用混入在另一個導入另一個組成部分,是作爲進口shared.html一樣簡單。

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

+0

爲什麼不讓每個組件聲明一個共享組件像http:// www .polymer-project.org /文檔/聚合物/ polymer.html#全球。這就是核心風格:https://github.com/Polymer/core-style/blob/master/core-style.html#L11 – ebidel

+0

你說得對,那會解決這個問題。沒有想到那個「核心風格」實際上表現得如此。我會相應地更新我的問題。 – PascalPrecht

+0

這句話'你只能在一個import中使用mixin'是不正確的。導入不會自動作用域。 –

回答

1

使用全局狀的部分是推薦的路要走。
使<name-you-like>並使用get/set來更改它(也可以使用屬性,雖然它們只是 sad 字符串)。

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的getter和他們一起玩/ 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.

+0

只是一個fyi,聚合物元素裏面的'

1

這是現在由Behaviors功能解決。

實施例:

我-behavior.html:

<script> 
    MyBehavior = { 
    properties: {}, 
    listeners: [], 
    _myPrivateMethod: function(){} 
    // etc. 
    }; 
</script> 

我-element.html:

<link rel="import" href="my-behavior.html"> 

<script> 
    Polymer({ 
    is: 'my-element', 
    behaviors: [MyBehavior] 
    }); 
</script> 

我-另一element.html:

<link rel="import" href="my-behavior.html"> 

<script> 
    Polymer({ 
    is: 'my-other-element', 
    behaviors: [MyBehavior] 
    }); 
</script> 
相關問題