【发布时间】:2012-03-27 21:56:00
【问题描述】:
我正在使用 d3.js 以 svg 呈现世界地图(使用 https://github.com/johan/world.geo.json/blob/master/countries.geo.json 表示功能)。我将渲染逻辑封装在主干视图中。当我渲染视图并将其附加到 DOM 时,我的浏览器中没有显示任何内容,尽管在查看生成的 HTML 时正确生成了 SVG 标记。当不封装在 Backbone.View 中时,这可以很好地呈现。这是我使用 Backbone.view 的代码:
/**
* SVG Map view
*/
var MapView = Backbone.View.extend({
tagName: 'svg',
translationOffset: [480, 500],
zoomLevel: 1000,
/**
* Sets up the map projector and svg path generator
*/
initialize: function() {
this.projector = d3.geo.mercator();
this.path = d3.geo.path().projection(this.projector);
this.projector.translate(this.translationOffset);
this.projector.scale(this.zoomLevel);
},
/**
* Renders the map using the supplied features collection
*/
render: function() {
d3.select(this.el)
.selectAll('path')
.data(this.options.featureCollection.features)
.enter().append('path')
.attr('d', this.path);
},
/**
* Updates the zoom level
*/
zoom: function(level) {
this.projector.scale(this.zoomLevel = level);
},
/**
* Updates the translation offset
*/
pan: function(x, y) {
this.projector.translate([
this.translationOffset[0] += x,
this.translationOffset[1] += y
]);
},
/**
* Refreshes the map
*/
refresh: function() {
d3.select(this.el)
.selectAll('path')
.attr('d', this.path);
}
});
var map = new MapView({featureCollection: countryFeatureCollection});
map.$el.appendTo('body');
map.render();
这是不使用 Backbone.View 的代码
var projector = d3.geo.mercator(),
path = d3.geo.path().projection(projector),
countries = d3.select('body').append('svg'),
zoomLevel = 1000;
coords = [480, 500];
projector.translate(coords);
projector.scale(zoomLevel);
countries.selectAll('path')
.data(countryFeatureCollection.features)
.enter().append('path')
.attr('d', path);
我还附上了生成的 SVG 标记的屏幕截图。知道这里可能出了什么问题吗?
编辑 - 这是根据请求最终解决此问题的覆盖 make 方法:
/**
* Custom make method needed as backbone does not support creation of
* namespaced HTML elements.
*/
make: function(tagName, attributes, content) {
var el = document.createElementNS('http://www.w3.org/2000/svg', tagName);
if (attributes) $(el).attr(attributes);
if (content) $(el).html(content);
return el;
}
【问题讨论】:
-
鉴于 make 方法已被删除,现在做这件事的正确方法是什么?
标签: javascript html svg backbone.js d3.js