我正在使用模板重复来生成项目列表。 这里简单的问题如何在我的'addme'方法中检索我点击的'item' 我可以在控制台中看到我的打印件
这是我的代码
<template repeat="{{item in items}}">
<div on-click="{{addme}}" layout horizontal justified>
<div>{{item.name}}</div>
<core-icon icon="settings"></core-icon>
</div>
</template>
addme(event, details,node){
print(event);
print(details);
print(node.selec);
selectedExercises.add(ex);
}
干杯
答案 0 :(得分:2)
来自this answer:
使用模板中的template-value属性:
<template repeat="{{item in items}}">
<div on-click="{{addme}}" layout horizontal justified template-value="{{item}}">
<div>{{item.name}}</div>
<core-icon icon="settings"></core-icon>
</div>
</template>
在事件处理程序中使用nodeBind:
import 'package:template_binding/template_binding.dart' as tb;
addme(event){
tb.TemplateInstance ti = tb.nodeBind(e.target).templateInstance; // get access to the TemplateInstance of the element
// TemplateInstance provides access to the model and the actual value
var ex = ti.model.value;
selectedExercises.add(ex);
}
答案 1 :(得分:2)
有很多方法!取决于您真正需要的数据类型。例如,如果您可以使用名称(或其他标识信息)跟踪item
实例,则可以执行以下操作:
<template repeat="{{item in items}}">
<div on-click="{{addme}}" data-item-name="{{item.name}}" layout horizontal justified>
<div>{{item.name}}</div>
<core-icon icon="settings"></core-icon>
</div>
</template>
然后在事件处理程序中:
addme(event, details, target){
String name = target.dataset['item-name'];
// then find your item instance using "name"
}
或者您可以为商品创建自定义元素,可能是<item-view>
,然后重复这些元素。
<template repeat="{{item in items}}">
<item-view item="{{item}}"></item-view>
</template>
这样可以更轻松,更清晰地获取所需的item
实例,因为target
将包含一个包含引用的公共属性。如果您希望了解该方法的更全面的示例,请与我们联系。
您甚至可以使用枚举来执行此操作,这将允许您在repeat
内获取索引,并且可以使用相同的索引在原始item
中查找List
实例1}}(假设它&#39; sa List
你重复过来)。看起来像这样:
<template repeat="{{item in items | enumerate}}">
<div on-click="{{addme}}" data-index="{{item.index}}" layout horizontal justified>
<div>{{item.value.name}}</div>
<core-icon icon="settings"></core-icon>
</div>
</template>
您可以在addme()
内获取索引,如:
int index = int.parse(target.dataset['index']);
困惑了吗?总是这么多办法,呃?
答案 2 :(得分:0)
聚合物&gt; = 1.0.0
@reflectable
void someClickHandler(dom.Event event, [_]) {
// for native events (like on-click)
var model = new DomRepeatModel.fromEvent(event);
// or for custom events (like on-tap, works also for native events)
var model = new DomRepeatModel.fromEvent(convertToJs(event));
var value = model.jsElement['items'];
// or
var value = model.jsElement[$['mylist'].attributes['as']];
// if you used the `as="somename"`
// in your <core-list> or <template is="dom-repeat">
}
有一个与自定义事件相关的未解决问题:https://github.com/dart-lang/polymer-dart/issues/624