Tôi đang sử dụng d3.js để hiển thị bản đồ thế giới bằng svg (sử dụng https://github.com/johan/world.geo.json/blob/master/countries.geo.json cho các đối tượng địa lý). Tôi đang đóng gói logic hiển thị trong dạng xem xương sống. Khi tôi hiển thị chế độ xem và đính kèm nó vào DOM, không có gì hiển thị trong trình duyệt của tôi, mặc dù đánh dấu SVG được tạo chính xác khi xem HTML được tạo. Điều này làm cho tốt khi không đóng gói trong một Backbone.View. Dưới đây là mã của tôi sử dụng Backbone.view:SVG không hiển thị đúng như chế độ xem xương sống
/**
* 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();
Dưới đây là đoạn code mà làm việc, mà không sử dụng 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);
Tôi cũng kèm theo một ảnh chụp màn hình của đánh dấu SVG tạo ra. Bất kỳ ý tưởng gì có thể xảy ra ở đây?
Edit - Đây là làm cho ghi đè phương pháp mà kết thúc giải quyết này, theo yêu cầu:
/**
* 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;
}
Cảm ơn! Tôi overrode 'làm' trong quan điểm của tôi và sử dụng createElementNS với 'http://www.w3.org/2000/svg' thay vì createElement và điều đó dường như làm các trick. Đánh giá cao hướng dẫn. –
@rr: bạn có thể đăng phương thức tạo của mình ở đâu đó không? –
@PierreSpring: Xong, không chắc chắn về mức độ liên quan của phiên bản này với các phiên bản Backbone mới hơn, tôi vẫn chưa theo kịp. –