问题
I have a polymer element called his-service:
<polymer-element name="gis-service" attributes="response url">
<template>
<style>
</style>
<core-ajax id="ajax"
auto
url="{{url}}"
method="get"
contentType = 'application/json'
on-core-response="{{postsLoaded}}"
body="{{body}}"
handleAs="xml">
</core-ajax>
</template>
<script>
Polymer('gis-service', {
created: function() {
this.response = [];
},
postsLoaded: function() {
this.response = [];
this.labels = [];
this.coordinates = [];
x = this.$.ajax.response.getElementsByTagName("CustomerServiceCenterData");
for (i=0;i<x.length;i++) {
if (x[i].getElementsByTagName("language")[0].innerHTML == "EN")
{
this.labels[i] = x[i].getElementsByTagName("label")[0].innerHTML;
this.coordinates.push({
lat:x[i].getElementsByTagName("lat")[0].innerHTML,
lng:x[i].getElementsByTagName("lng")[0].innerHTML
})
}
}
console.log(this.coordinates);
}
});
</script>
</polymer-element>
In the index file, I try to access the object labels and coordinates. The following is part of the index:
<gis-service id="gservice" response="{{labels}}" url="someUrl">
</gis-service>
<script>
var gis_service = document.querySelector('gis-service');
console.log(gis_service);
</script>
As you can see, I am trying to access labels and coordinates through querySelector. However, When I try to get labels for instance via:
gis_service.labels
It gives me undefined. The same thing with the variable coordinates. I can see the two variables when I do: console.log(gis_service), but cannot access them. Any help is appreciated.
回答1:
Define it outside of the function and then you should be able to use it externally. This format will work for the .8 version. 1.0 version will need to use the new format.
created: function() {
this.response = [];
},
labels: undefined,
postsLoaded: function() {
回答2:
You should read about databinding here
Don't do this:
<core-ajax id="ajax"
auto
url="{{url}}"
method="get"
contentType = 'application/json'
on-core-response="{{postsLoaded}}"
body="{{body}}"
handleAs="xml">
</core-ajax>
Do this instead:
<core-ajax id="ajax" auto url="{{url}}" method="get" contentType ='application/json' on-core-response="{{postsLoaded}}" body="{{body}}" handleAs="xml"></core-ajax>
Putting the bindings on different lines isnt supported yet
回答3:
There is other ways you can try to access the values, try
var yourElement = document.getElementById('gservice');
if This doesn't work, try with 'querySelector' as shown below:
<gis-service id="gservice" class="gservice"
response="{{labels}}" url="someUrl">
</gis-service>
<script>
var gis_service = document.querySelector('gservice');
console.log(gis_service);
</script>
See the additional class attribute.
Also i recommend you to upgrade to Polymer 1.0, because it allows more robust ways to do things...
来源:https://stackoverflow.com/questions/30534940/polymer-access-polymer-element-objects