聚合物阵列在更改时不会更新 UI

Polymer array won't update UI when changed

今天有很多 Polymer 1.0 问题,

我的 HTML 看起来像这样:

<section class="layout vertical" id="onlineList">
        <paper-item class="subdue layout horizontal center">Online Now</paper-item>
        <template is="dom-repeat" items="{{cats}}" as="cat">
            <paper-item>{{cat}}</paper-item>
        </template>
</section>

如您所见,我试图循环出数组 cats 中的每个 cat。我的问题是 cats-array 改变了大约 4 次。第一次它有一个 cat,第二次有两个..等等,直到没有更多的变化。但似乎传播到 UI 的唯一变化是第一个 cat.

cats 数组在名为 presenceChanged 的回调中发生变化,当 "online"-列表发生变化时,PubNub 会调用该回调,见下文:

template.presenceChanged = function(e) {
    var l = template.$.sub.presence.length;
    var d = template.$.sub.presence[l - 1];

    // who are online
    if(d.action === 'join') {
        if(d.uuid.length > 35) { // console
            d.uuid = 'the-mighty-big-cat';
        }
        onlineUuids.push(d.uuid);
    } else {
        var idx = onlineUuids.indexOf(d.uuid);
        if(idx > -1) {
            onlineUuids.splice(idx, 1);
        }
    }

    // display at the left column
    template.cats = onlineUuids;

    //.. some code
};

所以,澄清一下。 presentChanged-回调被调用,比方说 4 次。每次列表都会包含一只猫(因此它会为 "room" 中的每个用户调用一次)。在 "last" 调用中,它看起来像:["cat_1","cat_2","cat_3","cat_4"] 但只有 ["cat_1"] 会显示 UI-wise,为什么? :/

您需要使用 Polymer 元素提供的数组变异方法(参见 dom-repeat 上的 docs):

Mutations to the items array itself (push, pop, splice, shift, unshift) must be performed using methods provided on Polymer elements, such that the changes are observable to any elements bound to the same array in the tree. For example

在您的示例中,您需要在实际数组上使用 this.push('cats', d.uuid); 而不是 push 方法。 (同样适用于 splice,等等)