Polymer 1.0 observers - not working on array

五迷三道 提交于 2019-12-23 10:00:03

问题


I set an observer on to catch all polymer recognized events on an property that is an array, but I catch get it to catch the change. In my example below my observer function "bigup" only gets called on when the property, "bigs" is first initialzed.

<dom-module id="parent-page">
<template>
    <paper-button on-click="updateAll">Update</paper-button>
</template>
<script>
    var temp=[];
    temp.push({'conversation':[{'message':'hello'}]});

    Polymer({
        is: 'parent-page',
        properties: {
            bigs: {
                type: Array,
                value: temp
            }
        },
        observers: [
            'bigup(bigs.*)'
        ],
        updateAll: function(){
            this.bigs.push({'conversation':[{'message':'hola'}]});
            console.dir(this.bigs);
        },
        bigup: function(){
            console.log('big Up');
        }
    });
</script>

I also tried to use bigs.push in the observer but had no success. One part I don't understand is that if I add the following line to my "updateAll" function, the observer catches the change and fires "bigup".

this.bigs=[];

回答1:


You need to use the push method from Polymer instead of doing this.bigs.push.

So replace that line of code with

this.push('bigs', {'conversation':[{'message':'hola'}]});

For more info have a look at this link.




回答2:


For me this article was helpful as well, it covers both the way to register the observer as well as the splices methods as suggested by Justin XL.

Registering the observer:

properties: {
    users: {
      type: Array,
      value: function() {
        return [];
      }
    }
  },

  observers: [
    'usersAddedOrRemoved(users.splices)'
  ],

Calling splices methods the Polymer 1.0 way:

this.push('users', 'TestUser');

https://www.polymer-project.org/1.0/docs/devguide/properties.html#array-observation

FYI - this will NOT work in all cases (my initial idea) When you register the observer in the property declaration like this:

 properties: {
        users: {
          type: Array,
          value: function() {
            return [];
          },
          observer: 'usersAddedOrRemoved'
        }
      },

In this case the usersAddedOrRemoved method is only called when you assign a new array to the users object. It will not however fire when you mutate the array by pushing, popping, splicing etc.



来源:https://stackoverflow.com/questions/32215861/polymer-1-0-observers-not-working-on-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!