Polymer:当数组中的对象被外部代码修改时,更新dom重复元素
Polymer: Update dom-repeated elements when objects in an array are modified by outside code
我使用dom repeat列出数组中的一堆对象。数组由外部代码提供,因此修改不使用Polymer的array API。
这是一把小提琴,展示我的作品。有更好(更干净)的方法来处理这个问题吗?
html
<base href="https://polygit.org/polymer+:master/components/">
<link href="polymer/polymer.html" rel="import">
<dom-module id="example-element">
<template>
<div style="width:100px;height:100px;background-color: cadetblue" on-tap="onTap">click me</div>
<template is="dom-repeat" items="{{items}}" as="item">
<div>[[item.id]]</div>
</template>
</template>
</dom-module>
<example-element></example-element>
js
//an array managed by code outside of this component.
var GLOBAL_ARRAY = [
{id: 1},
{id: 2}
];
Polymer({
is: 'example-element',
properties: {
items:Array
},
ready: function() {
this.items = GLOBAL_ARRAY;
},
onTap: function(evt) {
//hold onto the old value before updating.
var oldValue = GLOBAL_ARRAY[0];
//just changing the property doesn't work regardless which notify is used below.
//GLOBAL_ARRAY[0].id = Math.round(Math.random() * 50);
//replacing the entire object works with notifySplices() below.
GLOBAL_ARRAY[0] = {id:Math.round(Math.random() * 50)};
console.log('changed the first items id to ', GLOBAL_ARRAY[0].id);
//doesn't work
//this.notifyPath('items', GLOBAL_ARRAY);
//works
this.notifySplices('items', [{
index:0,
object:this.items,
addedCount:1,
removed:[oldValue],
type:'splice'
}]);
}
});
我觉得在这里使用notifySplices()是错误的,因为我在技术上根本没有拼接。我本来希望notifyPath()能工作,但它没有。
解决方案是使用修改的对象属性的完整路径调用notifyPath。修订后的JS代码如下。
//an array managed by code outside of this component.
var GLOBAL_ARRAY = [
{id: 1},
{id: 2}
];
Polymer({
is: 'example-element',
properties: {
items:Array
},
ready: function() {
this.items = GLOBAL_ARRAY;
},
onTap: function(evt) {
GLOBAL_ARRAY[0].id = Math.round(Math.random() * 50);
this.notifyPath('items.0.id', GLOBAL_ARRAY[0].id);
}
});
正在工作的小提琴。
相关文章:
- 当客户端将两个按钮的javascript函数参数修改为相同时,SQL/PHP会更新多行
- 如何以良好的性能更新修改后的字符串
- 修改作用域变量后,未更新作用域绑定
- 修改req.url;t更新url参数(req.query)
- Polymer:当数组中的对象被外部代码修改时,更新dom重复元素
- AngularJS:深度对象修改后视图不更新
- 修改其<源>元素的 src 属性后,视频不会更新
- 如何修改我的 jQuery 以更新以不同方式激活的切换按钮上的 html
- 挖空文本输入修改可观察不更新文本
- 创建 Google 脚本,以便在日历活动更新时对其进行修改
- 当表单被 js 动态修改时,如何更新 yiiactiveform 设置
- 为什么当媒体查询更新 CSS 规则时,修改 CSS 规则会失败
- 挖空样式绑定在修改基础数据时不更新
- 更新/修改从dojo数据存储/JsonRestStore检索到的对象
- 如何在angular js中修改和更新数据表行
- 工厂中与控制器作用域绑定的已修改数据不会更新
- EmberJS -在渲染前修改模型并在更新时重置
- 如何在修改对象后更新html中的数据
- 在Ember中,我如何在ArrayController的内容被修改后更新视图
- {{警报更新.currentPage}} in指令在angular-route中每修改一次路由