2017-03-16 47 views
2

我有一個JSON文件(包含整數數組),我向其發送<iron-ajax>請求並檢索響應。我想處理響應(一個整數數組),並通過單擊按鈕將整數數組中的所有值遞增1。遞增JSON數組中所有元素的值並使用Polymer組件顯示

<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 */ 

我的高分子定義:

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; 
    } 
}); 

每次我按一下按鈕,就應該由1

我的組件模板中增加價值我的JSON文件:

{ 
    "id": 4, 
    "data": { 
    "labels": ["acvc","b","a","b","a"], 
    "values": [[112,57,53,122,128,120,56]] 
    } 
} 

回答

1

推薦步驟:

  1. 創建<button>具有click -handler修飾的_simpleDataValuesA.data.values值:

    <button on-click="_incrementValues">Increment</button> 
    
  2. 在腳本中,定義click -handler如下(注:我們使用Array.prototype.map來更新每個值E中的數組):

    _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. 更新元素的<template>顯示這樣的數組值:

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

demo

+0

非常感謝你這對我的作品! @ tony19 –

+0

@AnkitaGavali沒問題:) – tony19