Polymer 1.0 iron-ajax call is made but on-response

2019-07-21 12:21发布

I have the following code

<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/iron-ajax/iron-ajax.html" />


<dom-module id="custom-Element">
    <iron-ajax auto
               url="http://api.openweathermap.org/data/2.5/forecast"
               params='{"q":"California"}'
               handle-as="json"
               on-response="handleResponse"
               last-response="{{ajaxResponse}}"></iron-ajax>
    <span>{{ajaxResponse.city.name}}</span>
    <script>
        Polymer({
            is: 'custom-Element',
            handleResponse: function ()
            {
                console.log('  blalba');
            },
            ready: function () {
                setInterval(function () { console.log(this.ajaxResponse); }, 1000);

            }
        });
    </script>
</dom-module>

My problem is even though the ajax call is happening and data is retrieved the on-response "handleResponse" method is never being fired and the "ajaxResponse" isn't being populated either. I tried looking at different tutorials and code demos but I can't seem to find what's wrong with my code.

标签: polymer-1.0
1条回答
倾城 Initia
2楼-- · 2019-07-21 12:49

When using a <dom-module The iron-ajax or anything else needs to go inside a <template as its placed in the shadow dom.

eg

<dom-module id="custom-Element">
    <template>
    <iron-ajax auto ..... >
    <span>{{ajaxResponse.city.name}}</span>
    </template>
..
...
.....
</dom-module>

Ill explain a bit further.

Because you are creating a dom-module custom-Element and you are calling it with <custom-Element></custom-element> to display the data anything inside dom-module needs to be inside a <template></template> so its placed in the shadow dom and registers the id name custom-Element.

Think of the html5 <video> tag

Now by doing

<video width="320" height="240" controls>
  <source src="movie.mp4" type="video/mp4">
</video>

it will play a video.

However when you inspect <video> you cant see any special css like for the play /stop pause buttons or any javascript because its placed in the Shadow Dom of the browser and its hidden away.

So the video tag its just a name build in the browser so you can use to play videos. To put that in the shadow dom you need a <template>

With polymer you do the same

<dom-module id="any-name">

<template>
...
</template>

</dom-module>

and to use it

<any-name></any-name>

same like the <video></video> tag in html5.

Good article here to read about web components and why templates are used

查看更多
登录 后发表回答