2

I have a JSON file (containing an integer array) to which a I send a <iron-ajax> request and retrieve the response. I want to process the response (an the integer array) and increment all the values in the integer array by one on a button-click.

Every time I click the button, it should increment the value by 1.

My element template:

<iron-ajax
         url="/api/time-series/simple-data/4"
         last-response="{{_simpleDataValuesA}}"
         auto>
</iron-ajax>

<h1> /* Where I would like the entire updated array to be shown when I press the BUTTON to increment */

My Polymer definition:

 Polymer({

    is: 'new-page',
    properties: {
        _simpleDataValuesA: {
            type: Object
        },
        _cal: {
            type: Array,
            computed: 'cal_incr(_simpleDataValuesA)'
        }
    },
    cal_incr:function(_simpleDataValuesA){
        var a = this._simpleDataValuesA.data.values[0];
        a.forEach(function increment(item,index,a) {
            a[index]+=1;
        })
        console.log('array -- >',a);
        console.log('this._simpleDataValuesA.data.values[0] -- >',this._simpleDataValuesA.data.values[0]);
        this._simpleDataValuesA.data.values[0]=a;

        return this._simpleDataValuesA.data.values;
    }
});

My JSON File:

{
  "id": 4,
  "data": {
    "labels": ["acvc","b","a","b","a"],
    "values": [[112,57,53,122,128,120,56]]  
  }
}
tony19
  • 125,647
  • 18
  • 229
  • 307

1 Answers1

1

Recommended steps:

  1. Create a <button> that has a click-handler that modifies the values of _simpleDataValuesA.data.values:

    <button on-click="_incrementValues">Increment</button>
    
  2. In your script, define that click-handler as follows (Note: We use Array.prototype.map to update each value in the array):

    _incrementValues: function() {
      var a = this._simpleDataValuesA.data.values[0];
    
      // Update the array with incremented values
      this._simpleDataValuesA.data.values[0] = a.map(function(item) {
        return item + 1;
      });
    
      // Bypass Polymer's dirty-check (in order to notify the
      // data bindings) by assigning the property to an empty
      // object and then itself.
      var copy = this._simpleDataValuesA;
      this._simpleDataValuesA = {};
      this.set('_simpleDataValuesA', copy);
    }
    
  3. Update your element's <template> to display the array values like this:

    <ul>
      <template is="dom-repeat" items="[[_simpleDataValuesA.data.values.0]]">
        <li>[[item]]</li>
      </template>
    </ul>
    

demo

tony19
  • 125,647
  • 18
  • 229
  • 307