【问题标题】:How to Call Function on Each dom-repeat Element如何在每个 dom-repeat 元素上调用函数
【发布时间】:2020-08-24 01:15:18
【问题描述】:

我试图在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

【问题讨论】:

    标签: polymer-2.x dom-repeat


    【解决方案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)
    }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2011-03-23
        • 1970-01-01
        • 1970-01-01
        • 2020-03-18
        • 1970-01-01
        • 2019-06-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多