Bindings when elements are bound to same object in

2019-08-02 13:43发布

问题:

I have a situation where I have multiple elements which are bound to the same path and thus the same JS object underneath. Because of this, changes to the object at one place are immediately visible by the other element (though it doesn't know it). The documentation says I need to manually alert the system about this or use a automatic binding, which I am. So a notifyPath call is happening.

In the notifyPath DOM traversal it eventually nears the element which should react to the change, however the notifyPath code does a check to see if the element already knows about the change. In my case, because they are both pointing to the same JS object the old value is already the new value because they're literally the same object in memory. This stops the propagation of the change.

I've submitted this issue as a potential problem but curious about ways around it in the meantime.

Here is a JSBin of the issue: http://jsbin.com/hemexifami/2/edit?html,output

This seems like this kind of thing would be a common case. I've tried manually notifyPath-ing in the console directly on the element, passing it the array, however the code just sees that old is new (since they are both the same JavaScript Array and so it doesn't actually do anything. The documentation says it should return an indication of this but it actually doesn't. See my bug about that here.

Have any of you fought this before? Thanks in advance for any help!

回答1:

Polymer doesn't observe Object references per se, instead, for performance, it tracks changes to objects based on how you name them and how they relate to each other in the tree.

The section here in the dev guide discusses how to use the array-selector element to coordinate between selections in arrays and object bindings:

https://www.polymer-project.org/1.0/docs/devguide/templates.html#array-selector

If we add an array-selector element that knows about card.sections it will produce a bindable version of currentSection for you.

<array-selector id="selector" items="{{card.sections}}" selected="{{currentSection}}"></array-selector>

We also add a bit of code to tell the selector which item to select when the index changes:

    observers: [
      '_selectSection(card.sections, currentSectionIndex)'
    ],

    _selectSection(sections, index) {
      this.$.sectionSelector.select(sections[index]);
    }        

Here is a modification of your jsbin using array-selector: http://jsbin.com/qidehe/edit?html,output