Polymer:当数组中的对象被外部代码修改时,更新dom重复元素

Polymer: Update dom-repeated elements when objects in an array are modified by outside code

本文关键字:修改 更新 dom 元素 代码 外部 数组 对象 Polymer      更新时间:2023-09-26

我使用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);
  }
});

正在工作的小提琴。