在此示例(Plunk)中,属性和数组项之间存在绑定。
firstName应该从' John'到'测试'点击,但它没有发生。
如何让属性更改项目更新?
<script src="http://www.polymer-project.org/1.0/samples/components/webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="http://www.polymer-project.org/1.0/samples/components/polymer/polymer.html">
<!--
<link rel="import" href="https://cdn.rawgit.com/download/polymer-cdn/1.1.4/lib/paper-input/paper-input.html" />
-->
<dom-module id="first-el">
<template>
<br> firstName should change on click:<br><br>
firstName: <span>{{employees.employees.0.firstName}}</span>
<br>
<br>
<button on-tap="tap_change_firstName_1">change firstName to: Test</button>
</template>
<script>
(function() {
'use strict';
Polymer({
is: "first-el",
properties: {
employees: {
type: Object,
notify: true,
},
},
//domReady:
attached: function() {
this.async(function() {
console.log('first: domReady:');
this.employees = {
"employees": [{
"firstName": "John",
"lastName": "Doe"
}]
};
});
},
tap_change_firstName_1: function() {
console.log('First: tap_change_firstName_1');
//update array item property
this.set('employees.employees.0.firstName', 'Test');
console.log('New value:');
console.log(this.employees.employees[0].firstName);
//here the value is cnahged but that does not reflect in the DOM
},
});
})();
</script>
</dom-module>
<!-- use the element -->
<first-el></first-el>
更新
array-selector(simple example)元素也可用于此任务。
答案 0 :(得分:2)
set()
便利功能只包含属性设置器和notifyPath
调用。当你的数据是这样的数组时,我相信notifyPath
期待上层数组本身而不仅仅是它的一个片段。
解决问题的一种方法(可能有一些)是在直接设置属性后自己调用notifyPath
。
this.employees.employees[0].firstName = 'Test';
this.notifyPath('employees.employees', this.employees.employees);
请参阅新的Plunker。
答案 1 :(得分:1)
上层解决方案仅适用于一次更改,但不适用于多个名称&#39;更新,例如:Plunk
正确的解决方案,来自文档:在此Plunk
<div>{{arrayItem(myArray.*, 0, 'name')}}</div>
...
// first argument is the change record for the array change,
// change.base is the array specified in the binding
arrayItem: function(change, index, path) {
// this.get(path, root) returns a value for a path
// relative to a root object.
return this.get(path, change.base[index]);
},
...
// change a subproperty
this.set('myArray.1.name', rnd_firstName);