如何对每个 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

您可以遍历如下节点:

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)
}
您可以在

循环中添加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();
}

最新更新