2015-07-03 85 views
0

最初的目的是爲聚合物元素提供可配置的圖像位置。看來我明白了一些錯誤,並沒有把它做成「聚合物的方式」。問題在於如何實現這個目標,以及如果方法是正確的。v1.0元素中的聚合物元素訪問屬性

從調用頁面:

<mycustom-element imagelocation="/correct/path/to/images"></mycustom-element> 

和元素:

<link rel="import" href="proper/path/to/iron-image/iron-image.html"> 

<dom-module id="mycustom-element"> 
    <style> 
    :host { 
     display: block; 
    } 
    </style> 
    <template> 
    <iron-flex-layout class="layout horizontal wrap top-level-menu"> 
     <iron-image src="{{getLocation('image_file_name.png')}}"></iron-image> 
    </iron-flex-layout> 
    </template> 
</dom-module> 
<script> 
    (function() { 
    Polymer({ 
     is: 'mycustom-element', 
     properties: { 
     imagelocation: { 
      type: String, 
      value: "/wrong/path/to/images" 
     } 
     }, 
     ready: function() { 
     console.info('RD', this.imagelocation); 
     }, 
     getLocation: function(imageFilename) { 
     console.info('GLOC', this.imagelocation); 
     console.info('GLOC_PROP', this.properties.imagelocation.value); 
     return this.imagelocation + '/' + imageFilename.trim(); 
     } 
    }); 
    })(); 
</script> 

,我有是在瀏覽器上查看時,的「this.imagelocation」的值是問題默認的一個,不是從調用頁面提供的。

在控制檯輸出如下:

GLOC undefined 
GLOC_prop /wrong/path/to/images 
RD /correct/path/to/images 

徘徊什麼是錯的?它是否與元素的生命週期有關?函數調用可以延遲嗎?

回答

1

其實你有點回答你自己的問題。 FWIW,預期您的原始代碼中的行爲 - 並且您認爲這是由於Polymer的生命週期行爲所致。當您綁定

<iron-image src="{{getLocation('image_file_name.png')}}"></iron-image> 

計算功能,當在該函數的所有屬性準備節點被蓋章。在上述情況下,您實際上傳遞了一個固定變量,該變量始終爲「就緒」,因此<mycustom-element>的創建和就緒回調之間的一段時間,getLocation()已被調用,這可能在imagelocation發佈屬性的默認值之前或之後爲set - 聚合物屬性的默認值也設置在創建和準備之間 - 導致競爭條件。

在您的具體情況,「高分子路」將申報<iron-image>這樣

<iron-image src="{{getLocation(imagelocation, 'image_file_name.png')}}"></iron-image> 

getLocation()計算函數可能是這個樣子

getLocation: function (l, f) { 
    return (l + "/" + f.trim()); 
} 

使用這種方式時,因爲imagelocation是你計算函數的一個參數,你可以保證getLocation()只叫之後imagelocation發佈屬性的默認值已正確設置。

0

我花了一些時間,寫在這裏發生的事情爲他人的利益:

當「的getLocation」之稱,它是從「鐵圖像」的情況下調用。看起來鐵圖像繼承了父元素,但由於沒有提供任何屬性,它保留了原始值「/ wrong」,並且沒有更新到正確的值。提供的值不傳播。

一種解決方法是調用從模板的上下文中調用的「getLocation('image_file_name.png',imagelocation)」,因此它具有更新因此正確的值。

如果還有另一種更合適的方法,請給出建議。