【问题标题】:How to include multiple D3 charts in a Backbone view?如何在主干视图中包含多个 D3 图表?
【发布时间】:2016-10-23 20:35:25
【问题描述】:

如何在主干视图中包含多个 D3(可重复使用)图表?

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

通过这个例子你可以看到:

  • 可以有多个图表。
  • 类名在控制台中呈现,但不使用图表函数呈现。
  • 使用“图表”类名称调用函数时,将显示匹配数量的图表(来自 JSON 对象)。

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

  • 让每个图表显示在一个 div 中,模型的 id 作为 div 的类名。这是模板:

    <div class="b <%= id %>"></div>
    
  • 图表应该在 html 中指定类名后呈现。如果这样做,您怎么知道?

'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>

【问题讨论】:

    标签: d3.js backbone.js


    【解决方案1】:

    据我所知,图表函数是在视图实际附加到具有类“a”的 div 之前被调用的。我做了一些编辑(搜索 edit_cmets 文本),当我运行 sn-p 时它似乎可以工作。

    //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>

    【讨论】:

      猜你喜欢
      • 2012-05-28
      • 1970-01-01
      • 2014-01-28
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多