2015-07-03 86 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)”,因此它具有更新因此正确的值。

如果还有另一种更合适的方法,请给出建议。