聚合物1.x:数据结构阵列 [英] Polymer 1.x: Databinding Arrays

查看:160
本文介绍了聚合物1.x:数据结构阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要选择选择的属性在这个元素到DOM(在$ code>< div> [[selected]]< / div> )。

I want to databind the selected property in this element to the DOM (at <div>[[selected]]</div>).

选择状态(如Texas)后,我希望状态的名称显示在科罗拉多州,南达科他州的预选状态(< div> [[selected]]< / div> 标签内)。但是,它不是。

After selecting a state (like "Texas"), I expect the state's name to appear in the upper left next to the pre-selected states of "Colorado,South Dakota" (inside the <div>[[selected]]</div> tag). But instead, it does not.

这里发生了什么?如何成功地将DOM数据绑定到选定的属性?并且每个新的状态被自动更新,并且被选中。

What's going on here? How can I successfully databind the DOM to the selected property? And have the DOM update automatically with each new state that is selected and de-selected.

按照以下步骤操作:


  1. 打开此jsBin

  2. 请注意预先选定的州是科罗拉多州和南达科他州。

  3. 通知Colarado和南达科他州列在左上角。

  4. 点击德克萨斯州

  5. 观察得克萨斯州状况在图表中选中。

  6. ❌注意到德州 不包括在左上方所选状态列表中。即,< div> [[selected]]< / div>

  7. 点击标有显示值的按钮,在控制台中,Texas被包含在选定的数组中。

  1. Open this jsBin.
  2. Observe the pre-selected states are Colorado and South Dakota.
  3. Notice Colarado and South Dakota are listed in the upper left.
  4. Click Texas.
  5. Observe the state of Texas is selected in the chart.
  6. ❌ Notice the state of Texas is not included in the list of selected states in the upper left. i.e., <div>[[selected]]</div>
  7. Click the button labeled "Show Values" and observe in the console that "Texas" is included in the selected array.



使用.slice()的尝试解决方案崩溃



这个答案解释了为什么突变的数组不能被Polymer对象直接观察到


...你正在做聚合物看不到的工作(即数组操作),然后询问设置来确定发生了什么。但是,当您调用 this.set('selected',selected); 时,Polymer会看到的身份被选择没有改变(也就是说,它与之前的Array对象一样),它只是停止处理。

...you are doing work where Polymer cannot see it (i.e. the array manipulations), and then asking set to figure out what happened. However, when you call this.set('selected', selected);, Polymer sees that the identity of selected hasn't changed (that is, it's the same Array object as before) and it simply stops processing.

所以我试图解决通过使用原始数组上的 .slice()方法创建一个新数组的问题如下。

So I attempted to solve the problem by creating a new array using the .slice() method on the original array as follows.

// Sort new 'selected' array
_selectedChanged: function(selectedInfo) {
  var selected = this.selected.slice();
  selected.sort();
  //this.set('selected', selected); // Uncommenting this line crashes call stack
},

这似乎解决了可观察性问题但是会产生一个副作用问题并且崩溃了调用堆栈。

This seems to solve the observability problem but creates a side effect issue and crashes the call stack.

<!DOCTYPE html>

<head>
  <meta charset="utf-8">
  <base href="https://polygit.org/components/">
  <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
  <link href="polymer/polymer.html" rel="import">
  <link href="google-chart/google-chart.html" rel="import"> </head>

<body>
  <dom-module id="x-element"> <template>
      <style>
        google-chart {
          width: 100%;
        }
      </style>
    <br><br><br><br>
    <button on-tap="_show">Show Values</button>
    <button on-tap="clearAll">Clear All</button>
    <button on-tap="selectAll">Select All</button>
    <div>[[selected]]</div>
    <google-chart id="geochart"
                  type="geo"
                  options="[[options]]"
                  data="[[data]]"
                  on-google-chart-select="_onGoogleChartSelect">
    </google-chart>
    </template>
    <script>
      (function() {

        // google-chart monkey patch
        var gcp = Object.getPrototypeOf(document.createElement('google-chart'));
        gcp.drawChart = function() {
          if (this._canDraw) {
            if (!this.options) {
              this.options = {};
            }
            if (!this._chartObject) {
              var chartClass = this._chartTypes[this.type];
              if (chartClass) {
                this._chartObject = new chartClass(this.$.chartdiv);
                google.visualization.events.addOneTimeListener(this._chartObject,
                    'ready', function() {
                        this.fire('google-chart-render');
                    }.bind(this));

                google.visualization.events.addListener(this._chartObject,
                    'select', function() {
                        this.selection = this._chartObject.getSelection();
                        this.fire('google-chart-select', { selection: this.selection });
                    }.bind(this));
                if (this._chartObject.setSelection){
                  this._chartObject.setSelection(this.selection);
                }
              }
            }
            if (this._chartObject) {
              this._chartObject.draw(this._dataTable, this.options);
            } else {
              this.$.chartdiv.innerHTML = 'Undefined chart type';
            }
          }
        };

        Polymer({
          is: 'x-element',
          /** /
           * Fired when user selects chart item.
           *
           * @event us-map-select
           * @param {object} detail Alpabetized array of selected state names.
          /**/
          properties: {
            items: {
              type: Array,
              value: function() {
                return [ 'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming', ].sort();
              },
            },
            color: {
              type: String,
              value: 'blue',
            },
            options: {
              type: Object,
              computed: '_computeOptions(color)',
            },
            selected: {
              type: Array,
              value: function() {
                return [];
              }
            },
            data: {
              type: Array,
              computed: '_computeData(items, selected.length)'
            },
          },
          observers: [
            '_selectedChanged(selected.length)',
          ],
          _computeOptions: function() {
            return {
              region: 'US',
              displayMode: 'regions',
              resolution: 'provinces',
              legend: 'none',
              defaultColor: 'white',
              colorAxis: {
                colors: ['#E0E0E0', this.color],
                minValue: 0,  
                maxValue: 1,
              }
            }
          },    
          // On select event, compute 'selected'
          _onGoogleChartSelect: function(e) {
            var string = e.path[0].textContent.split('Select')[0].trim(), // e.g. 'Ohio'
                selected = this.selected, // Array of selected items
                index = selected.indexOf(string);
            // If 'string' is not in 'selected' array, add it; else delete it
            if (index === -1) {
              this.push('selected', string);
            } else {
              this.splice('selected', index, 1);
            }
          },
          // Sort new 'selected' array
          _selectedChanged: function(selectedInfo) {
            var selected = this.selected.slice();
            selected.sort();
            //this.set('selected', selected); // Uncommenting this line crashes call stack
          },
          // After 'items' populates or 'selected' changes, compute 'data'
          _computeData: function(items, selectedInfo) {
            var data = [],
                selected = this.selected,
                i = items.length;
            while (i--) {
              data.unshift([items[i], selected.indexOf(items[i]) > -1 ? 1 : 0]);
            }
            data.unshift(['State', 'Select']);
            return data;
          },
          clearAll: function() {
            this.set('selected', []);
          },
          selectAll: function() {
            this.set('selected', this.items);
          },
          _show: function() {
            //console.log('items', this.items);
            console.log('selected', this.selected);
            //console.log('data', this.data);
          },
        });
      })();
    </script>
  </dom-module>
  <x-element color="red" selected='["Colorado", "South Dakota"]'></x-element>
</body>

</html>


推荐答案

如果你想绑定数组,你必须使用重复重复

If you want to bind array you have to use the dom-repeat.

<template is="dom-repeat" items="[[selected]]">[[item]] </template>

http://jsbin.com/soxedeqemo/edit?html,console,output

这篇关于聚合物1.x:数据结构阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆