Solved

How to mutate Polymer v1.x property inside ajax request

Posted on 2016-11-11
11
20 Views
Last Modified: 2016-11-20
I'm trying to populate an array based in the results that I fetch from an Ajax request via iron-ajax When I try to Access to my property, my watch window displays "not available"

Below is an little example I recreated for explain my issue:

my-component.html
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/iron-ajax/iron-ajax.html">
<link rel="import" href="../../bower_components/app-storage/app-localstorage/app-localstorage-document.html">
<link rel="import" href="../../bower_components/paper-dropdown-menu/paper-dropdown-menu.html">


<dom-module id="my-component">
    <template>
        <div>
            <paper-dropdown-menu
                    id="location" label="Ubicaci&oacute;n"
                    value="{{vehicle.location}}">
            </paper-dropdown-menu>
            <paper-dropdown-menu id="city" label="Ciudad">
                <paper-menu
                        class="dropdown-content"
                        selected="{{city.city_code}}"
                        attr-for-selected="value"
                        on-iron-select="estadoSeleccionado">
                    <template id="" is="dom-repeat" items="[[opcionesDisponibilidad]]" as="i">
                        <paper-item value="[[i.valor]]">[[i.texto]]</paper-item>
                    </template>
                </paper-menu>
            </paper-dropdown-menu>
        </div>
        <iron-ajax
                id="ajax"
                method="GET"
                url="http://localhost:8080/ws.asmx"
                params=""
                content-type="application/x-www-form-urlencoded; charset=UTF-8"
                handle-as="text"
                on-response="handlecities"
                debounce-duration="300">
        </iron-ajax>
        <app-localstorage-document id="localStorageElement" key="myapp.login_data" data="{{loginInfo}}"></app-localstorage-document>
    </template>
    <script>
        Polymer({
            is: "my-component",
            properties:{
                vehicle: {
                    type: Object,
                    value:{
                        id: "",
                        plate: "",
                        location: ""
                    }
                },
                cities:{
                    notify: true,
                    type: Array,
                    value: [{city_code:'0', city_name:'-'}]
                }
            },
            ready:function () {
                this.querycities();
            },
            querycities: function () {
                if (this.$.localStorageElement.storage['myapp.login_data']){
                    this.$.loginInfo = JSON.parse(this.$.localStorageElement.storage['myapp.login_data']);
                } else return false;
                this.$.ajax.url = this.$.ajax.url + "/listadoCiudades";
                this.$.ajax.verbose = true;
                this.$.ajax._boundHandleResponse = this.handlecities;
                this.$.ajax.params = {dispositivo:'12345', credencial: this.$.loginInfo.cred};
                this.$.ajax.generateRequest();
            },
            handlecities: function (request) {
                console.log(request.response);
                var xPath = new SoftXpath();
                xPath.registerNamespace("","");
                xPath.loadXML(request.response);
                var cities = xPath.selectNodes("//Ciudad//*[self::Codigo|self::Nombre]");
                var xPathElement = new SoftXpath();
                if (cities){
                    for(var i = 1; i < cities.length;i++){
                        var c = new Object();
                        c.Codigo = cities[i-1].text;
                        c.Nombre = cities[ i ].text;

                        this.$.cities.push(c);// <---- Here I have not access to my polymer property ' cities '.

                        //How to update my polymer var cities ??
                        //Tried also with:
                        // this.cities --> undefined
                        // this.$$('#myassignedId').cities  --> undefined
                    }
                }
            }
        })
    </script>
</dom-module>

Open in new window


How can I populate my 'cities' property if appears out of scope ?
Seems as when the flow passes thought iron-ajax, the main properties are lost
0
Comment
Question by:rdfloc
  • 6
  • 5
11 Comments
 
LVL 82

Expert Comment

by:leakim971
ID: 41884140
0
 

Author Comment

by:rdfloc
ID: 41884147
yes.. I tried. But as stated in my post, at that point "this.cities" is undefined so "this.cities.push(c);" produces an error.
0
 
LVL 82

Expert Comment

by:leakim971
ID: 41884170
I don't like your line 74 and so on...
could you change the name of this variable?

 
              var __cities = xPath.selectNodes("//Ciudad//*[self::Codigo|self::Nombre]");
                var xPathElement = new SoftXpath();
                if (__cities){
                    for(var i = 1; i < __cities.length;i++){
                        var c = new Object();
                        c.Codigo = __cities[i-1].text;
                        c.Nombre = __cities[ i ].text;

                        this.cities.push(c);// <---- Here I have not access to my polymer property ' cities '.

Open in new window

0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 

Author Comment

by:rdfloc
ID: 41884183
Changed as suggested. But no luck.

handlecities: function (request) {
                console.log(request.response);
                var xPath = new SoftXpath();
                xPath.registerNamespace("","");
                xPath.loadXML(request.response);
                var __cities  = xPath.selectNodes("//Ciudad//*[self::Codigo|self::Nombre]");
                var xPathElement = new SoftXpath();
                if (__cities){
                    for(var i = 1; i < cities.length;i++){
                        var c = {};
                        c.Codigo = __cities[i-1].text;
                        c.Nombre = __cities[i].text;
                        this.cities.push(c);
                    }
                }
            },

Open in new window

Still an error in my console:

ReferenceError: cities is not defined
0
 
LVL 82

Expert Comment

by:leakim971
ID: 41884191
could you share a page to see that ?
0
 

Author Comment

by:rdfloc
ID: 41884214
Hmm. Impossible at this moment, as the target will be a Hybrid application mounted in mobile device. I´m  doing my initial development in localhost.
0
 
LVL 82

Expert Comment

by:leakim971
ID: 41884253
Could you be sure your cache is cleared :)
0
 
LVL 82

Expert Comment

by:leakim971
ID: 41885287
so let say if not defined yet.
do it :

if(!this.cities)
   this.cities = [];
this.cities.push(c);

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
ID: 41888726
no more news ? If you check documentation, you see only :
this.cities = foo;

no example like :
this.cities.plush(foo);
0
 

Accepted Solution

by:
rdfloc earned 0 total points
ID: 41888764
Well,
After too many try-error variations, finally I found the cause of error.

Line 65: this.$.ajax._boundHandleResponse = this.handlecities;
Removed that line and all my polymer attributes returned to normality.

I was using that sentence because I was trying to reuse the component for several ajax requests. 'handlecities' is specified as attribute as well, so is redundant (only when there are no intentions of reuse). I still don´t know how to reuse the component defining a custom handler, but for some reason if i use the above sentence, all polymer properties are lost.

So, in the meantime I´m defining several ajax components one for each ajax request.
0
 

Author Closing Comment

by:rdfloc
ID: 41894671
I found the solution by myself after too many try error variations.
0

Featured Post

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
how i fix Remove render-blocking JavaScript 3 62
file upload jquery, send variables 3 26
How to position loader with CSS 3 41
html Uncheck Checkbox 2 13
Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
jQuery is a JavaScript library that greatly simplifies JavaScript programming. AJAX is an acronym formed from "Asynchronous JavaScript and XML."  AJAX refers to any communication between client and server, when the human client does not observe a…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question