D3 with Backbone / D3 with Angular / D3 with Ember?

后端 未结 7 934
孤独总比滥情好
孤独总比滥情好 2020-12-23 12:24

I\'m working on a medium sized application that is going to include a lot of D3 charts / interactions in it. I\'m wondering if anyone has tried to use Backbone, Angular, or

7条回答
  •  时光取名叫无心
    2020-12-23 13:18

    We used d3 with Backbone pretty extensively on a project that consisted of multiple "scenes". Each scene contained a set of different charts, and a user has the ability navigate from one scene to another. These scenes and their content all needed to be highly configurable (e.g. label colors and formatting, or indicating which data params should be plotted on a given axis).

    D3 (rightfully) doesn't provide a view management system, which is where Backbone took over. Backbone Views served as wrappers for d3 charts. Predictably, Backbone Models served as the carriers of the d3-plotted data. But more interestingly, we also found that they served well as a means of controlling the appearance and behavior of the d3 code contained within the Backbone Views; essentially they served as view models. Since d3 promotes passing functions as arguments into other functions, these Backbone Models-as-view-models ended up holding many functions in them.

    The following is a simplistic example, but picture doing this with dozens of properties. Using coffeescript here, because it's shorter (and better).

    First, there's the model, which we instantiate inside (for example) a router's event handler. We populate this model with functions that will be applied to d3 selectors.

    barChartModel = new Backbone.Model
      barColor: (d, i) -> if d.profits < 0 then "red" else "green"
      barLengthVal: (d, i) -> return bar.profits #// profits will be the prop we graph
      onClick: (d, i) ->
        console.log "We are", if d.profits <= 0 then "losing" else "making", "money"
      data: someJsonWeLoaded
    

    We pass this model into a new view:

    barChartView = new BarChartView
      el: "#the_bar_chart"
      model: barChartModel
    

    A view might be implemented like this:

    class BarChartView extends Backbone.View
      render: ->
        bars = d3.select(@el)
          .selectAll('.bar')
          .data(@model.get 'data') # <---- THIS
    
        bars.enter()
          .attr('class', 'bar')
          .attr('fill', @model.get 'barColor') # <---- THIS
          .attr('height', (d, i) ->
            @barLengthScale @model.get('barLengthVal')(d, i) # <---- AND THIS
          )
          .on('click', @model.get 'onClick') # <---- INTERACTIVITY TOO
    
      initialize: ->
        @barLengthScale = d3.scale.linear()
          .domain([-100, 100]) # <---- THIS COULD ALSO COME FROM MODEL
          .range([0, @$el.height()])
        @render()
    

提交回复
热议问题