Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering in Backbone.js using d3.js and svgs

In backbone.js, a view's render function generates unattached html which can be later attached to the dom.

Currently, I have to have an existing target in the HTML for me to append a svg to. I then use the data/enter pattern to insert elements into the svg. Is there a way to get d3.js to generate the svg without attaching it to the dom?

var svg = d3.select("#target").append('svg')
    .attr("viewBox","0 0 100 100"); 

svg.selectAll("circle")
    .data(data)
    .enter().append("circle")
        .attr("r", 10)
        .style("fill", "black");

Alternatively, is it possible to provide d3 with a unattached dom element to append stuff to? Something like this? D3.js documentation suggests that select can accept nodes, but the following does not work for me either

var svg = d3.select(this.$el).append('svg')  // Uncaught TypeError: Object [object Object] has no method 'appendChild' 
    .attr("viewBox","0 0 100 100");     

svg.selectAll("circle")
    .data([1,2,3])
    .enter().append("circle")
        .attr("r", 10)
        .style("fill", "black");
like image 611
kumikoda Avatar asked Jun 13 '12 21:06

kumikoda


People also ask

Does D3 js use SVG?

To create SVG using D3. js, let us follow the steps given below. Step 1 − Create a container to hold the SVG image as given below. Step 2 − Select the SVG container using the select() method and inject the SVG element using the append() method.

What is render in Backbone JS?

render() The Backbone. js render method overrides itself with your code that renders the view template from model data and updates this with new HTML. It contains the logic for rendering the template which constructs the view.

What can you use D3 js for?

D3 is a JavaScript library and framework for creating visualizations. D3 creates visualizations by binding the data and graphical elements to the Document Object Model. D3 associates (binding) the data (stuff you want to visualize) with the DOM. This allows the user to manipulate, change or add to the DOM.

How do I import D3 into JavaScript?

Install D3 by running npm install d3 --save . Import D3 to App. js by adding import * as d3 from d3 . You need to use import * (“import everything”) since D3 has no default exported module.


1 Answers

I found the answer in this post SVG not rendering properly as a backbone view

d3.select(this.el) 

does the trick!

like image 105
kumikoda Avatar answered Sep 25 '22 20:09

kumikoda