Polymer event parameters on repeat

这一生的挚爱 提交于 2019-12-11 05:18:09

问题


I am working on Polymer and pretty new in this.

I have a list which iterates using a template. There needs to be a remove button on that. On click of remove I am calling a function. How do we know which list item was called so that I can have the item to remove.

<template repeat="{{ data in listData }}">
<div>
   <img src="../../Styles/images/edit.png" alt="">
   <img src="../../Styles/images/remove.png" alt="">
</div>
</template>

I was doing the remove like this before

<img src="../../Styles/images/remove.png" alt="" id="data.id" on-click={{remove}}"">

So, on remove function I get the Id using the event parameter in the function handler. Now, I have this edit as well. So, now in the same approach, i will have an id for the edit as below.

<img src="../../Styles/images/edit.png" alt="" id="data.id" on-click={{remove}}"">

Since both ids cannot be same, I can append some text also along with the id to make it different. However I am not in favour of this approach. Can anyone throw some light on how to respond to events within a repeat template so that we can know which item was called for.

Thanks, Sumesh


回答1:


The target field of the event passed to the event handler refers the item. The templateInstance of the element refers the bound model.

selectStory: function(e, detail, sender) {
  var story = e.target.templateInstance.model.s;
  console.log("Clicked " + story.headline);
  this.loadStory(story.id); // accessing non-rendered data from the model
}

see also https://www.polymer-project.org/docs/polymer/databinding.html (bottom of the page)

You could also go with your approach and just use another attribute name. Binding to id is discouraged anyway as far as I know.




回答2:


I thought I would post an update for those using Polymer 1.x.

The event argument passed to your declarative event handler now has a model attribute on it.

Example:

<template is="dom-repeat" items="{{listData}}">
  <div>
    <img src="../../Styles/images/edit.png" alt="">
    <img src="../../Styles/images/remove.png" alt="" on-click="_remove">
  </div>
</template>

<script>
  Polymer({
    ...

    _remove: function(e) {
      // item from listData available in e.model
    }
  });
</script>

More info here: https://www.polymer-project.org/1.0/docs/devguide/templates.html#handling-events



来源:https://stackoverflow.com/questions/28210278/polymer-event-parameters-on-repeat

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!