问题
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