我有一个使用 Polymer 的应用程序。在此应用程序中,我将一组项目绑定(bind)到 UI。用户可以单击按钮。单击该按钮时,将调用与第三方库关联的任务。当该任务完成时,它会返回一个状态。我需要将该状态绑定(bind)到数组中项目的属性。第三方库允许我使用回调函数。因此,我将使用 JavaScript 内置的 setTimeout
函数来演示我的挑战。
my-component.html
<dom-module id="view-tests">
<template>
<table>
<tbody>
<template is="dom-repeat" items="{{ items }}" as="item">
<tr>
<td>[[ item.name ]]</td>
<td><item-status status="[[ item.status ]]"></item-status></td>
</tr>
</template>
</tbody>
</table>
<button on-click="bindClick">Bind</button>
</template>
<script>
Polymer({
is: "my-component",
properties: {
items: {
type: Array,
notify: true,
value: function() {
return [
new Item({ name:'Item 1', status:'In Stock' }),
new Item({ name:'Item 2', status:'Sold Out' })
];
}
},
},
bindClick: function() {
var items = items;
setTimeout(function() {
this.set('items.1.status', 'In Stock');
}, 1000);
}
});
</script>
</dom-module>
如上面的代码片段所示,还有另一个组件item-status
。
item-status.html
<dom-module id="test-status">
<template>
<span class$="{{ statusClass }}">{{ status }}</span>
</template>
<script>
Polymer({
is: "item-status",
properties: {
status: {
type: String,
value: '',
observer: '_statusChanged'
}
},
_statusChanged: function(newValue, oldValue) {
alert(newValue);
if (newValue === 'In Stock') {
this.statusClass = 'green';
} else if (newValue === 'Sold Out') {
this.statusClass = 'red';
} else {
this.statusClass = 'black';
}
}
});
</script>
</dom-module>
当用户单击“绑定(bind)”按钮时,用户界面中的状态不会更新。我注意到我为调试目的添加的 alert
在 View 最初加载时出现。但是,单击“绑定(bind)”按钮时不会出现警报
窗口。这意味着观察者函数没有触发。我的回调实际上看起来像这样:
getStatus(1, function(status) {
this.set('items.1.status', status);
});
如何通过回调设置数组项的属性?
最佳答案
setTimeout 有其自己的范围。 '.bind(this)' 可用于将 Polymer 元素范围绑定(bind)到回调函数。下面的bindClick函数应该可以工作
bindClick: function() {
setTimeout(function() {
this.set('items.1.status', 'In Stock');
}.bind(this), 1000);
}
工作 jsbin: http://jsbin.com/mehovu/edit?html,output
关于javascript - 在Polymer回调中设置数组项属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33236553/