Polymer - How do I attach an observer to an array?

Deadly 提交于 2019-12-22 05:15:22

问题


How do I attach an observer to a polymer attribute that is an array? To be clear, I want callbacks when items in the array change. For simplicity, let's say my array is:

[
    { text: 'foo' },
    { text: 'bar' }
]

I want something like:

observe : {
    'items.text' : 'itemsChanged'
}

The following works, but is obviously un-sustainable:

observe : {
    'items[0].text' : 'itemsChanged',
    'items[1].text' : 'itemsChanged'
}

Note that in my case, the changes are coming from another polymer element that I have control over. So if I could somehow trigger a change from the element that has control over { text: 'foo' }, that would work as well.


回答1:


To be clear, Polymer will automatically observe Arrays, but an 'ArrayObserver' will only tell you if (a) the Array itself is replaced or (b) items are added, removed, or rearranged. Just like observed objects, Polymer does not automatically observe properties of sub-objects.

the changes are coming from another polymer element that I have control over

This is usually the case and we typically have the element doing the changing fire an event for communication.




回答2:


You can use Object.observe() to accomplish this. e.g.:

ready: function() {
    Object.observe(this.items, this.myObserver);
}
myObserver: function (changes){
    changes.forEach(function(change, i){
        console.log('what property changed? ' + change.name);
        console.log('how did it change? ' + change.type);
        console.log('whats the current value? ' + change.object[change.name]);
        console.log(change); // all changes
    });
},

More here.




回答3:


Kinda late, but because the question ranks quite high on google and none of the above is really helping, here is my solution:

Polymer ships with observe.js and this helps solving your problem.

The basic version would be to use the ArrayObserver but this only fires when the array gets altered, meaning when elements are added, removed and i guess also when you replace an entry. But this won't help if you wanna observe changes to object properties in an array - such as in your case.

Here it's better to use the CompoundObserver and add all paths via addPath or addObserver(new PathObserver(obj, '...')). But you have to iterate over the whole array and add all observed properties in a loop for instance.



来源:https://stackoverflow.com/questions/24639507/polymer-how-do-i-attach-an-observer-to-an-array

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