Here is a Plunker sketch of my problem
相关代码,包含Polymer模板及其调用:
<link rel="import"
href="http://www.polymer-project.org/1.0/components/polymer/polymer.html">
<dom-module id="polymer-d3-component">
<template>
<style>
#monthChart .line {
stroke: rgb(247, 150, 29);
stroke-width: 2;
fill: none;
}
#monthChart .axis {
shape-rendering: crispEdges;
}
#monthChart .x.axis line {
stroke: rgba(88, 89, 93, .12);
}
#monthChart .x.axis .minor {
stroke-opacity: .5;
}
#monthChart .x.axis path {
display: none;
}
#monthChart .y.axis line, .y.axis path {
fill: none;
stroke: rgba(88, 89, 93, .5);
}
#monthChart .axis path,
#monthChart .axis line {
fill: none;
stroke: rgba(88, 89, 93, .3);
shape-rendering: crispEdges;
}
#monthChart .axis text {
font: 10px sans-serif;
fill: rgba(88, 89, 93, .5);
}
</style>
<div id="monthChart"></div>
</template>
<script>
Polymer({
is: "polymer-d3-component",
ready: function() {
var m = [20, 20, 20, 20];
var w = 850 - m[1] - m[3];
var h = 400 - m[0] - m[2];
var data=[24509, 19466, 18004, 18381, 17312, 19926, 24761, 24815, 24333, 29117, 24527, 17478];
function formatCurrency (d) {
return "$" + d;
}
var xLabels = d3.time.scale().domain([new Date(2013, 0, 1), new Date(2013, 11, 31)]).range([0, w]);
var x = d3.scale.linear().domain([0, data.length]).range([0, w]);
var y = d3.scale.linear().domain([0, d3.max(data)]).range([h, 0]);
var line = d3.svg.line()
.x(function(d, i) {
return x(i);
})
.y(function(d) {
return y(d);
})
var graph = d3.select(this.$.monthChart).append("svg")
.attr("width", w + m[1] + m[3])
.attr("height", h + m[0] + m[2])
.append("g")
.attr("transform", "translate(" + 120 + "," + m[0] + ")");
var xAxis = d3.svg.axis().scale(xLabels).ticks(d3.time.months).tickFormat(d3.time.format("%B")).tickSize(-h).tickSubdivide(true);
graph.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + h + ")")
.call(xAxis);
var yAxisLeft = d3.svg.axis().scale(y).ticks(7).tickFormat(formatCurrency).orient("left");
graph.append("g")
.attr("class", "y axis")
.attr("transform", "translate(-25,0)")
.call(yAxisLeft);
graph.append("path")
.attr("d", line(data))
.attr('class', 'line');
}
})
</script>
</dom-module>
SVG错误,但样式也未应用,可以看出形状全部为黑色且许多未正确绘制。如果我使用SVG代码并手动将其直接放在Polymer组件中,它可以正常工作。
可能会发生什么?
答案 0 :(得分:2)
当模板呈现给DOM时,Polymer应用样式,因此稍后(例如在ready
)中由库附加的DOM节点不会被样式化。这被描述为in the manual here。
修复是调用 -
this.scopeSubtree(this.$.monthChart, true);
- ready
的开头。这告诉Polymer观察给定的子树进行更改,并在其他库附加节点时应用给定的样式,例如D3。