2017-03-16 42 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