javascript - polymer 和D3 : How to send JSON from element attribute to template

标签 javascript html json d3.js polymer

我是 polymer 新手,我正在尝试将 D3 与其集成。我修改了现有的要点,但我有点困惑。 我正在尝试将一些 JSON 从 HTML 中的 Polymer 元素属性 (barData) 传递到 polymer 模板。 JSON 作为 String 传递并解析为计算属性 (data)。我已将一些默认值放入 barData 属性中,但希望每次使用 barData 属性创建新元素时都覆盖这些默认值。这是行不通的。我创建了另一个名为 test 的属性,它仅将字符串传递给段落中显示的测试属性。这很好用吗?我是否遗漏了一些明显的东西?

index.HTML:

<!DOCTYPE html>
<html>
  <head>
    <script src="bower_components/webcomponentsjs/webcomponents-lite.min.js"></script>
    <link rel="import" href="elements/bar-chart2.html">
  </head>
  <body>
    <!--creates chart but with template data set although the test attribute does work-->
    <bar-chart2 barData='[{"letter":"C","frequency":".76"},{"letter":"D","frequency":".03"}]' test="CHEEP"></bar-chart2>
    <!--creates chart but with template data set-->
    <!--<bar-chart2 barData="http://codepen.io/superpikar/pen/kcJDf.js"></bar-chart2>-->
  </body>
</html>

bar-chart2.html:

<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/iron-input/iron-input.html">
<script type="text/javascript" src="../bower_components/d3/d3.min.js"></script>

<polymer-element name="bar-chart2" attributes="barData">
    <template>
        <div id="chart" class="poly-bars">{{barData}}<p>{{test}}</p></div>
<!--the chart will use the new data after input but I want it to happen on create -->
        <div>
            <input is="iron-input" bind-value="{{barData}}" placeholder="paste data here">
        </div>
    </template>

    <script>
        function Bars(opts) {
            opts = opts || {};
            var margin = opts.margin || {
              top: 20,
                right: 20,
                bottom: 30,
                left: 40
            };
            var width = 960 - margin.left - margin.right;
            var height = 500 - margin.top - margin.bottom;
            var title = opts.title || 'Bar Chart';

            var formatPercent = d3.format('.0%');

            var xValue = function(d) {
                    return d.letter;
                }, // data -> value
                xScale = d3.scale.ordinal().rangeRoundBands([0, width], .1), // value -> display
                xMap = function(d) {
                    return xScale(xValue(d));
                }, // data -> display
                xAxis = d3.svg.axis().scale(xScale).orient('bottom');

            var yValue = function(d) {
                    return d.frequency;
                }, // data -> value
                yScale = d3.scale.linear().range([height, 0]), // value -> display
                yMap = function(d) {
                    return yScale(yValue(d));
                }, // data -> display
                yAxis = d3.svg.axis().scale(yScale).orient('left').tickFormat(formatPercent);

            function type(d) {
                d.frequency = +d.frequency;
                return d;
            }

            function bars(selection) {
                selection.each(function(d, i) {

                    var el = d3.select(this);

                    el.selectAll('svg').remove();

                    var svg = el.append('svg')
                        .attr('title', title)
                        .attr('width', width + margin.left + margin.right)
                        .attr('height', height + margin.top + margin.bottom)
                        .append('g')
                        .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

                    xScale.domain(d.map(xValue));
                    yScale.domain([0, d3.max(d, yValue)]);

                    svg.append('g')
                        .attr('class', 'x axis')
                        .attr('transform', 'translate(0,' + height + ')')
                        .call(xAxis);

                    svg.append('g')
                        .attr('class', 'y axis')
                        .call(yAxis)
                        .append('text')
                        .attr('transform', 'rotate(-90)')
                        .attr('y', 6)
                        .attr('dy', '.71em')
                        .style('text-anchor', 'end')
                        .text('Frequency');

                    svg.selectAll('.bar')
                        .data(d)
                        .enter().append('rect')
                        .attr('class', 'bar')
                        .attr('x', xMap)
                        .attr('width', xScale.rangeBand)
                        .attr('y', yMap)
                        .attr('height', function(d) {
                            return height - yMap(d);
                        });
                });
            }

            return bars;
        }

        Polymer({
            is: 'bar-chart2',
            properties: {
                test: {
                    type: String,
                    value: "BOOM"
                },
                barData: {
                    type: String,
                    value: '[{"letter":"A","frequency":".08167"},{"letter":"B","frequency":".01492"}]',
                    reflect: true,
                    notify: true
                },
                width: Number,
                height: {
                    type: Number,
                    value: 400
                },
                data: {
                    type: Array,
                    computed: '_parse(barData)'
                }
            },
            _parse: JSON.parse,

            observers: [
                'dataChanged(data)'
            ],

            created: function() {
                this.bars = new Bars(this);
            },

            dataChanged: function() {
                this._draw();
            },

            _draw: function() {
                if (!this.data) {
                    return;
                }
                if (!this.elem) {
                    return;
                }

                d3.select(this.elem)
                    .datum(this.data).call(this.bars);
            },

            ready: function() {
                this.elem = this.$.chart;
                this._draw();
            }
        });
    </script>
</polymer-element>

最佳答案

barData更改为bar-data

When mapping attribute names to property names:

  1. Attribute names are converted to lowercase property names. For example, the attribute firstName maps to firstname.

  2. Attribute names with dashes are converted to camelCase property names by capitalizing the character following each dash, then removing the dashes. For example, the attribute first-name maps to firstName.

请查看Polymer doc here .

关于javascript - polymer 和D3 : How to send JSON from element attribute to template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31677159/

相关文章:

javascript - jQuery:检查第一个单选按钮时显示 Div

javascript - 如何设置 jQuery 可调整大小的小部件以围绕中心调整大小

json - 我如何向 Web 服务器发出我正在发布 gzip 压缩数据的信号?

javascript - React.DOM : Unhandled Rejection (TypeError): Cannot read property 'map' of undefined

javascript - 如何将 setInterval 与我的表单一起使用来创建闹钟?

javascript - JQuery FadeIn 和 CSS 幻灯片是断断续续的

html - Bootstrap 3 : columns over columns

json - 需要帮助推断 NiFi 中 json 文件的 avro 架构

javascript - jquery数据属性不解析json字符串

javascript - C# 相当于 javascript 的 'const'