恐怕我不明白这个问题,罗曼。
我已经使用以下代码进行了测试:
<polymer-element name="my-component" attributes="status count">
<template>
<style>
</style>
<div >
<h1>You have {{ tasks.length }} tasks, {{ remaining }} remaining</h1>
<div
style="border: solid 1px red; padding: 20px; border-radius: 20px; display: inline-block;"
on-click="{{ doTask }}"
>
Click to mark as done
</div>
<div>
{{ tasks[0].done }}
</div>
</div>
</template>
<script>
Polymer("my-component", {
tasks: [
{name: "foo", done: false},
{name: "bar", done: true}
],
get remaining() {
return this.tasks.filter(function(t) { return !t.done }).length;
},
doTask: function() {
this.tasks[0].done = true;
}
});
</script>
</polymer-element>
当我单击按钮时,标签的值会发生变化,即remining
getter 检测到变化。我已经在 Linux 上的 Chromium 41 和 Firefox 中进行了测试。
您可以在http://embed.plnkr.co/HXaKsQHjchqwe0P3bjy5/preview上测试我的代码
您能否给我更多关于您想要做什么以及它与我的代码有何不同的信息?
编辑
在通过 Twitter 与@romaintaz 交谈后,似乎只有当按钮位于 if 模板中时才会出现问题,如下所示:
<div >
<h1>You have {{ tasks.length }} tasks, {{ remaining }} remaining</h1>
<template repeat="{{ task, taskIndex in tasks }}">
<template if="{{task.done}}">
<button
style="border: solid 1px red; padding: 20px; border-radius: 20px; display: inline-block;"
on-click="{{ doTask }}"
>Click 1</button>
</template>
<template if="{{!task.done}}">
<button
style="border: solid 1px red; padding: 20px; border-radius: 20px; display: inline-block;"
on-click="{{ doTask }}"
>Click 2</button>
</template>
</template>
<div>
{{ tasks[0].done }}
</div>
在这种情况下,removing
getter 不再检测列表项属性之一的更改。
目前我只有一个快速的'n'dirty解决方案:不要只更改列表项的一个属性,而是更改整个列表项,然后让getter看到它。
例子:
<polymer-element name="my-component" attributes="status count">
<template>
<style>
</style>
<div >
<h1>You have {{ tasks.length }} tasks, {{ remaining }} remaining</h1>
<template repeat="{{ task, taskIndex in tasks }}">
<template if="{{task.done}}">
<button
style="border: solid 1px red; padding: 20px; border-radius: 20px; display: inline-block;"
on-click="{{ doTask }}"
>Click 1</button>
</template>
<template if="{{!task.done}}">
<button
style="border: solid 1px red; padding: 20px; border-radius: 20px; display: inline-block;"
on-click="{{ doTask }}"
>Click 2</button>
</template>
</template>
<div>
{{ tasks[0].done }}
</div>
</div>
</template>
<script>
Polymer("my-component", {
tasks: [
{name: "foo", done: false},
{name: "bar", done: true}
],
get remaining() {
return this.tasks.filter(function(t) { return !t.done }).length;
},
doTask: function() {
tmp = this.tasks[0];
tmp.done = true
this.tasks[0] = {};
this.tasks[0] = tmp;
},
observe: {
tasks: 'validate'
},
validate: function(oldValue, newValue) {
}
});
</script>
</polymer-element>
戳这里: http ://embed.plnkr.co/YgqtKgYRaRTZmoKEFwBy/preview