与dom-repeat结合使用时,聚合物的数据绑定功能存在问题。我想知道自己缺少什么才能使这项工作。
数据绑定似乎在某些情况下使用repeat元素工作正常,例如带输入框。但是,在按钮上使用点击事件并在关联的项目对象上编辑字段似乎不会因某种原因而起作用。
这是我的SSCCE(Plunker:http://plnkr.co/edit/Vof1nYdDFR4Jg4ZXL9DI?p=preview):
index.html
==========
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script src="https://polygit.org/components/webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="dummy_element.html">
</head>
<body>
<p>Click the "Toggle" button to toggle between Edit and View modes.</p>
<dummy-element></dummy-element>
</body>
</html>
dummy_element.html
==================
<link rel="import" href="https://polygit.org/components/polymer/polymer.html">
<dom-module id="dummy-element">
<template>
<template is="dom-repeat" items="{{records}}">
<p>
<span hidden="{{item.editing}}">View mode: {{item.value}}</span>
<span hidden="{{!item.editing}}">Edit mode: <input value="{{item.value}}" /></span>
<button on-tap="onTap">Toggle</button>
</p>
</template>
</template>
<script>
Polymer({
is: 'dummy-element',
properties: {
records: {
type: Array,
value: function () {
return [
{value: '#1', editing: false},
{value: '#2', editing: true},
];
},
},
},
onTap: function (e) {
e.model.item.editing = !e.model.item.editing;
console.log('Editing:', e.model.item.editing);
},
});
</script>
</dom-module>
我的意图:我在Toggle按钮上的点击处理程序应该切换&#34;编辑&#34;对于相关行,在true和false之间标记,并且UI应自动更新以反映更改。
会发生什么:虽然底层模型似乎发生了变化,但UI不会重新绘制。
有什么建议吗?
答案 0 :(得分:2)
有两个问题。首先,在onTap
处理程序中,您需要使用Polymer API来改变数组中的对象。
onTap: function (e) {
this.set("records." +e.model.index +".editing", !e.model.item.editing);
console.log('Editing:', e.model.item.editing);
},
正如Scarygami在评论中指出的那样,e.model
有自己的set
。所以上面也可以简化为:
onTap: function (e) {
e.model.set("item.editing", !e.model.item.editing);
console.log('Editing:', e.model.item.editing);
},
其次,要使数据绑定在原生input
元素上正常工作,您必须specify the target host event。
<input value="{{item.value::input}}" />
这是一个link到你的狙击手的叉子。