Polymer自定义元素属性访问或发送

szy*_*ski 2 shadow-dom polymer

我正在寻找一种方法来从DOM访问Polymer自定义元素的属性,或者将数据从Polymer.register发送到DOM.

下面这个非常简单的元素采用两个值并将它们相乘,将结果放在其result属性中.

如何从外部访问此结果?

<element attributes='value times result' name='value-box'>
  <template>
    <p>{{result}}</p>
  </template>

  <script>
    Polymer.register(this, {
      ready: function() {
        if (this.value != null && this.times != null) {
          this.result = this.value * this.times;
        }
      }
    });
  </script>
</element>
Run Code Online (Sandbox Code Playgroud)

ebi*_*del 6

resulttimes和你的元素一样的属性value.您可以从外部JS访问它,就像普通HTML元素上的任何属性一样.例如:

<value-box value="2" times="10"></value-box>
<script>
  document.querySelector('value-box').result;
</script>
Run Code Online (Sandbox Code Playgroud)

在元素内部,您想要的是将result计算属性保持最新为times/ value更改.有几种方法可以做到这一点.一个是使用<property>Changed观察者[ 1 ]:

<element name="value-box" attributes="value times result">
  <template>
    <p>result: {{result}}</p>
  </template>
  <script>
  Polymer.register(this, {
    valueChanged: function() {
      this.result = this.value * this.times;
    },
    timesChanged: function() {
      this.result = this.value * this.times;
    }
  });
  </script>
</element>
Run Code Online (Sandbox Code Playgroud)

演示:http://jsbin.com/idecun/2/edit

或者,您可以使用getter result:

  Polymer.register(this, {
    get result() {
      return this.value * this.times;
    }
  });
Run Code Online (Sandbox Code Playgroud)

演示:http://jsbin.com/oquv​​ap/2/edit

注意对于第二种情况,如果浏览器不支持Object.observe,Polymer将设置一个计时器进行脏检查result.这就是为什么你看到第二个例子在控制台中打印"here"的原因.在Chrome Canary中运行相同的功能,启用"实验性WebKit功能" about:flags,您将看不到计时器.我还等不及Object.observe到处都是另一个原因!:)

希望这可以帮助.

  • 我对此有点迟,但对于其他所有人都想知道这一点:$('value-box')返回一个jQuery集合而不是一个本机Element对象.要使它与jQuery一起使用,你必须使用$('value-box').get(0).result (2认同)