Reputation: 101
How do I access properties of parent or other elements in Polymer?
For example my top-most element is "my-app".
Now I am in an element called "my-element-1", how would I access/reference any properties from "my-app" using Javascript?
Further, if I am in "my-element-2", would I be able to access/reference properties of "my-element-1"?
EDIT: There are many reasons why I want to do this, and I certainly believe there are better ways than having to do this. But, I do not know the ways.
1: The first use case that comes to mind is that I use "iron-pages", which is located in a parent element. Each "page" is therefore a child of that parent.
The parent definitely knows which "page" is "selected" because the "iron-pages" is a property of the parent.
However, each "page" does not know if it is selected or no longer selected because the "selected" attribute is only known to the parent.
In this use case, I just want to be able to know from within the "page" whether it is still selected or not.
2: The second use case is probably a general design pattern. I want to maintain a set of GLOBAL properties, which can then be accessed anywhere from within the Polymer app. My assumption is that it should be store within "my-app" as the root element.
Upvotes: 1
Views: 1292
Reputation: 3662
1 In a closed parent-child pair like with the iron-pages
you can take advantage of the selectedAttribute and selectedClass properties. By setting one of them you can let the child "know" that it's selected.
2 The other example isn't so simple. For keeping shared state you can use the oxygen-state
element which was mentioned on Polymer's Slack recently. Similar solution is possible with iron-meta
which lets you access global variables.
The more robust solution to connecting elements app-wide is the Flux pattern. It appeared as a solution to a similar problem - communication between elements on a page. If elements are to communicate freely, it quickly can become unwieldy. You can read a number of related questions on SO: Flux architecture with polymer elements, Binding to global variables in Polymer, Polymer 1.0: How to pass an event to a child-node element without using <iron-signals>?
A simplification of this is to use events to notify any interested element of changes elsewhere in your application. A naive way is to listen for events on the document
. Then there is also the iron-signals
element.
Upvotes: 1