javascript - 更新模板 dom-repeat 项目中的数组未反射(reflect)到 dom

标签 javascript polymer

考虑这段代码:

<template is="dom-repeat" items="{{chats}}" as="item">
    <p>{{item.name}}</p>
    <span>{{item.unreadcount}}</span>
</template>

我似乎无法确保替换数组(完全替换,而不仅仅是更新其中一个元素的属性)会更新 dom。

更新我尝试这样:

var c = this.chats;
c.forEach(function(e) {
    e.unreadcount = Math.floor(Math.random() * 10) + 1;
}.bind(this));

// none of the following approaches has any effect:
this.chats = c;
this.set("chats", c);
this.notifyPath("chats", c);

如果数组完全改变,如何实现重新渲染 dom?

编辑

多亏了玛丽亚的提示,我知道了该怎么做。

仅使用 splice() 是不够的,还需要使用Polymer的函数来修改数组本身:this.set(..., ...) .

for (i = 0; i < this.chats.length; i++) { 
    this.set('chats.'+i+'.unreadcount', Math.floor(Math.random() * 10) + 1);
}
this.chats = this.chats.slice();

自从开始使用 Polymer 以来,由于我的头剧烈撞击墙壁,我的前额开始变平

最佳答案

这里的问题是,在所有这些操作之后,您的 chats 属性仍然是数组的同一个实例。在您尝试的任何方法中,Polymer 都会检查实例是否已更改,但不会检查数组中的项目是否发生更改。解决此问题的一种方法是创建数组的新副本并将其分配给聊天

this.chats = c.slice();

更新

虽然我很确定上面的方法在某些时候可以工作,但我可以确认它不再工作了。我假设 Polymer 以某种方式缓存了旧值。所以我认为您使用 set API 的解决方案是现在最好的方法。我发现以下方法也有效,但我猜它在大多数情况下效率较低。它重置数组,然后异步设置新值。在这种情况下,甚至不需要切片。

this.chats = [];

this.async(function() {
    this.set("chats", c);
});

关于javascript - 更新模板 dom-repeat 项目中的数组未反射(reflect)到 dom,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42333262/

相关文章:

javascript - 为什么在函数内部定义的 x 会成为全局变量,而我一开始就没有将其声明为变量?

javascript - 使用 CSS 或 Javascript 使圆形图像变暗

javascript - 从 gulp typescript js 流中分割 src 和测试文件

polymer 1.x : How to use Polyfills to shim support for CSS variables

javascript - 在 Polymer 中使用 core-ajax 的 CORS 错误

polymer - Iron-ajax 数据绑定(bind)

javascript - Web 组件就绪标志

javascript - 如何处理 webelement is - not attribute id(!) in javascript from selenium-python?

javascript - Polymer - 有人可以解释一下 this.$.foo.bar Polymer 中使用的 JavaScript 语法吗?

javascript - 如何使用 forEach 将数组中的字符串转换为数字?