如何在每个dom-repeat元素上调用函数

时间:2019-01-03 22:25:26

标签: polymer-2.x id dom-repeat

我正在尝试在dom-repeat模板内的每个元素上调用函数。

<dom-repeat items="[[cart]]" as="entry">
  <template>
    <shop-cart-item id="item"></shop-cart-item>
  </template>
</dom-repeat>

...

checkStatus() {
  this.$.item.doSomething();
}

如何在每个元素上调用doSomething

2 个答案:

答案 0 :(得分:-1)

您可以遍历以下节点:

checkStatus() {
  const forEach = f => x => Array.prototype.forEach.call(x, f);

  forEach((item) => {
    if(item.id == 'cartItem') {
      console.log(item);
      item.doSomething(); // call function on item
    }
  })(this.$.cartItems.childNodes)
}

答案 1 :(得分:-1)

您可以在循环中添加on-tap事件。为了观察您单击了哪个项目,请查看model属性:

<dom-repeat items="[[cart]]" as="entry">
  <template>
     <!-- need to give dynamic id for each item in dome-repeat -->
    <shop-cart-item id="[[index]]" on-tap = 'checkStatus'></shop-cart-item>

  </template>
</dom-repeat>

...

checkStatus(status) {
  console.log(status.model)  // you can get index number or entry's properties.
  this.$.item.doSomething();
}

编辑:

因此,根据@Matthew的评论,如果需要在dom-repeat的某个元素的函数中调用一个函数,则首先如上所述提供动态id name,然后:

checkStatus(status) {
  this.shadowRoot.querySelector('#'+ status.model.index).doSomething();
}
相关问题