v1.0 聚合物元素从元素访问属性

v1.0 polymer element access attribute from element

最初的目的是为聚合物元素提供可配置的图像位置。看来我是理解错了,没做"polymer way"。问题在于应该如何实现以及该方法是否正确。

来自调用页面:

<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

在徘徊是怎么回事?它与元素的生命周期有关吗?函数调用可以延迟吗?

我花了一些时间,为了他人的利益写下这里发生的事情:

当调用 "getLocation" 时,它是从 "iron-image" 的上下文中调用的。 iron image 似乎继承了父元素,但由于没有提供属性,它保留了原始值“/wrong”,并且没有更新为正确的值。提供的值不会传播。

一种解决方法是调用 "getLocation('image_file_name.png', imagelocation)",它是从模板的上下文中调用的,因此它具有更新后的正确值。

如有其他更合适的做法,请提出。

实际上你已经回答了你自己的问题。 FWIW,您的原始代码中的行为是预期的 - 您说这是由于 Polymer 的生命周期行为是正确的。当你绑定

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

计算函数,当该函数中的所有属性就绪[=36]时,节点将被标记=].在上面的例子中,你实际上传入了一个固定变量,它总是"ready",所以在<mycustom-element>的创建和准备回调之间的某个时间,getLocation()已经被调用,这可能是在 imagelocation 发布之前或之后设置 属性 的默认值 - Polymer 属性的默认值也设置在创建和就绪之间的某个位置 - 导致竞争条件。

在您的特定情况下,"polymer-way" 将像这样声明 <iron-image>

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

您的 getLocation() 计算函数可能看起来像这样

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

这样做,因为imagelocation是你的计算函数的一个参数,你可以保证getLocation()只在 [=15]之后被调用=] 已发布 属性 的默认值设置正确。