简体   繁体   中英

Polymer 1.0 Observe Array

I just tried to update my Polymer Website to version 1.0, but my array-observer-function does not work anymore. So I had a look in the docs and noticed, that there is a new way to observe push & pop changes.

To test these changes, I copied the code from the Polymer docs , but even that example doesn't work... Here is my try to test the example script:

<!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>

The javascript-console just says Uncaught TypeError: Cannot read property 'indexSplices' of undefined . Any ideas what is wrong?

The usersAddedOrRemoved function is firing at the start when the users array is created (with an undefined changeRecord). If you handle the undefined you'll see it works as expected and fires both at the start and on the user added.

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);
        }
    },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM