我正在用聚合物制作d3.js地图组件。拓扑数据需要从json文件中加载,而且由于我不希望组件依赖于URL/URI,所以我使用内联JSON而不是使用AJAX加载它:
<polymer-element name="map-us">
<template>
<script id="topodata" type="application/json" src="data/us.json"></script>
/* ... more stuff ... */
</template>
<script>
Polymer('map-us', {
ready: function() {
/*
This works in regular HTML/JQuery:
var x = JSON.parse($('#myJson').html());
console.log(x.arcs);
*/
var x = JSON.parse(this.$.topodata.html());
console.log(x.arcs);
});
</script>
</polymer-element>但是显然topdata元素没有html()方法。
这样做对吗?怎么处理这件事?
发布于 2014-07-23 03:43:46
不需要内联JSON文件。聚合物的resolvePath函数在这里很有用,可以确保JSON文件的相对路径总是正确的,而不管组件包含在哪里:
this.topojsonURI = 'data/us.json';
/* d3.json basically just makes the json call */
d3.json(this.resolvePath(this.topojsonURI), function() {
/* code rendering the map */
}关于resolvePath 这里的信息。
更新(聚合物1.0):
函数名已更改为resolveUrl:1.0 API文档
发布于 2014-07-08 16:40:14
您不依赖于外部资源,但它仍然位于单独的文件中。我会使用core-ajax加载它:
<core-ajax id="topodata" auto url="data/us.json" handleAs="json"
response="{{response}}"></core-ajax>
...
responseChanged: function() {
//this.response is your JSON
}http://www.polymer-project.org/docs/elements/core-elements.html#core-ajax
https://stackoverflow.com/questions/24636831
复制相似问题