聚合物1.0观察阵列

Polymer 1.0 Observe Array

本文关键字:阵列 观察 聚合物      更新时间:2023-09-26

我刚刚尝试将我的Polymer网站更新到1.0版本,但我的数组观察器函数不再工作。所以我看了一下文档,发现有一种新的方法可以观察push&弹出式更改。

为了测试这些更改,我从Polymer文档中复制了代码,但即使是那个例子也不起作用。。。以下是我测试示例脚本的尝试:

<!doctype html>
<html>
<head>
  <title>Test</title>
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes"> 
    <script src="/bower_components/webcomponentsjs/webcomponents-lite.min.js"></script>
    <link rel="import" href="/bower_components/polymer/polymer.html">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
    <my-index></my-index>
</body>
</html>
<dom-module id="my-index">
<script>
    Polymer({
        is: "my-index",
        properties: {
            users: {
                type: Array,
                value: function() {
                    return [];
                }
            }
        },
        observers: [
            'usersAddedOrRemoved(users.splices)'
        ],
        ready: function(){
            this.addUser();
        },
        usersAddedOrRemoved: function(changeRecord) {
            console.log(changeRecord);
            changeRecord.indexSplices.forEach(function(s) {
                s.removed.forEach(function(user) {
                    console.log(user.name + ' was removed');
                });
                console.log(s.addedCount + ' users were added');
            }, this);
        },
        addUser: function() {
            this.push('users', {name: "Jack Aubrey"});
        }
  });
</script>
</dom-module>

javascript控制台只显示Uncaught TypeError: Cannot read property 'indexSplices' of undefined。有什么想法吗?

usersAddedOrRemoved函数在创建users数组(带有未定义的changeRecord)时启动。如果您处理未定义的,您将看到它按预期工作,并在开始时和添加的用户时触发。

usersAddedOrRemoved: function(changeRecord) {
        console.log(changeRecord);
        if (changeRecord) {
            changeRecord.indexSplices.forEach(function(s) {
                s.removed.forEach(function(user) {
                    console.log(user.name + ' was removed');
                });
                console.log(s.addedCount + ' users were added');
            }, this);
        }
    },