如何在 Backbone 视图中包含多个 D3 图表?

How to include multiple D3 charts in a Backbone view?

如何在 Backbone 视图中包含多个 D3(可重用)图表?

代码示例试图在 Backbone 视图 (_view) 中呈现图表函数 (chart())。

通过例子你可以看出:

当在 _view.render 中调用图表函数时,预期输出为:

'className' 是否为 D3 选择器输出可读格式?

在 _view.render (chart(className)) 中调用的图表函数被注释掉,因为它不呈现。 (只是为了显示渲染的内容。)

关于如何呈现这些图表有什么想法吗?

//chart function

function chart(className){
  
var margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 100 - margin.left - margin.right,
    height = 200 - margin.top - margin.bottom;

var x = d3.scale.ordinal().rangeRoundBands([0, width], 100);

var y = d3.scale.linear().range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(5, "%");

var svg = d3.select(className).append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  x.domain("a");
  y.domain([0, 1]);

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis);

  svg.selectAll(".bar")
      .data([20])
    .enter().append("rect")
      .attr("class", "bar")
      .attr("x", 10)
      .attr("width", 20)
      .attr("y", 48)
      .attr("height", 100);
}

//multiple charts are possible
chart(".chart");
chart(".chart");


//model
  _model = Backbone.Model.extend({
    defaults: {
      title: null,
      body: null
    }
  });

//collection
  _collection = Backbone.Collection.extend({
    model: _model,
    url: 'http://jsonplaceholder.typicode.com/posts/'
  });

//properties of this url include userId, id, title, body

//view
  _view = Backbone.View.extend({
    tagName: 'div',
    className: 'container',
    template: _.template($('#template').html()),
    render: function() {
     var chartClassName = "." + this.model.attributes.id;
      this.$el.html(this.template(this.model.attributes));
      $('.b').html("Chart goes here");
     
      //logs chart class name
      console.log(chartClassName);
      
      //chart(chartClassName);
      return this;
    }
  });

//view
  _View = Backbone.View.extend({
    el: '.a',
    initialize: function() {
      this.collection = new _collection();
      this.collection.fetch({
        reset: true
      });
      this.render();
      this.listenTo(this.collection, 'reset', this.render);
    },
    render: function() {
      this.collection.each(function(item) {
        this.renderA(item);
      }, this);
    },
    renderA: function(item) {
      var __View = new _view({
        model: item
      });
      this.$el.append(__View.render().el);
    }
  });
  
  new _View();
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-1.11.3.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Adding a D3 chart to a Backbone template</title>
  <style>
  .bar {
  fill: green;
}

.axis {
  font: 10px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.x.axis path {
  display: none;
}
  </style>
</head>
<body>
  <div class="chart"></div>
  <div class="a"></div> 
<script type="text/template" id="template">
  <div class="b <%= id %>"></div>
  <p>Title: <%= title %></p>
  <p>Body: <%= body %></p>
</script>
</body>
</html>

据我所知,在使用 class 'a' 将视图实际附加到 div 之前调用了图表函数。我进行了一些编辑(搜索 edit_comments 文本),当我 运行 片段时它似乎起作用了。

//chart function

function chart(className){
  
var margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 100 - margin.left - margin.right,
    height = 200 - margin.top - margin.bottom;

var x = d3.scale.ordinal().rangeRoundBands([0, width], 100);

var y = d3.scale.linear().range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(5, "%");

var svg = d3.select(className).append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  x.domain("a");
  y.domain([0, 1]);

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis);

  svg.selectAll(".bar")
      .data([20])
    .enter().append("rect")
      .attr("class", "bar")
      .attr("x", 10)
      .attr("width", 20)
      .attr("y", 48)
      .attr("height", 100);
}

//multiple charts are possible
chart(".chart");
chart(".chart");


//model
  _model = Backbone.Model.extend({
    defaults: {
      title: null,
      body: null
    }
  });

//collection
  _collection = Backbone.Collection.extend({
    model: _model,
    url: 'http://jsonplaceholder.typicode.com/posts/'
  });

//properties of this url include userId, id, title, body

//view
  _view = Backbone.View.extend({
    tagName: 'div',
    className: 'container',
    template: _.template($('#template').html()),
    render: function() {
      /* edit_comments - chartClassName is used in the '_View' which appends to the DOM */
      this.chartClassName = ".b_" + this.model.attributes.id; /* edit_comments - added 'b_' to the class name string concat */
      this.$el.html(this.template(this.model.attributes));
     
      //logs chart class name
      console.log(this.chartClassName);
      
      //chart(chartClassName);
      return this;
    }
  });

//view
  _View = Backbone.View.extend({
    el: '.a',
    initialize: function() {
      this.collection = new _collection();
      this.collection.fetch({
        reset: true
      });
      this.render();
      this.listenTo(this.collection, 'reset', this.render);
    },
    render: function() {
      this.collection.each(function(item) {
        this.renderA(item);
      }, this);
    },
    renderA: function(item) {
      var __View = new _view({
        model: item
      });

      this.$el.append(__View.render().el);
      chart(__View.chartClassName);/* edit_comments - call chart after view is added to DOM */
    }
  });
  
  new _View();
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-1.11.3.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Adding a D3 chart to a Backbone template</title>
  <style>
  .bar {
  fill: green;
}

.axis {
  font: 10px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.x.axis path {
  display: none;
}
  </style>
</head>
<body>
  <div class="chart"></div>
  <div class="a"></div> 
<script type="text/template" id="template">
  <div class="b_<%= id %>"></div> <!-- edit_comments - added underscore to the class name -->
  <p>Title: <%= title %></p>
  <p>Body: <%= body %></p>
</script>
</body>
</html>