1

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

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Sumesh Kuttan
  • 1,333
  • 1
  • 17
  • 40

2 Answers2

4

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.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    works good. i tried both the approaches. i changed binding to custom named attributes and achieved it. thats when i saw your reply. the templateInstance seems to be cleaner and gives me information about my whole model. i tried it for demo and is woking.i am going that way. thanks Gunter. – Sumesh Kuttan Jan 29 '15 at 10:41
3

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

adam
  • 96
  • 1