ember-data as data for d3

2020-06-23 08:23发布

I would like to use my emberdata as data for creating objects within d3. I try to convert the items from the controllers model into new javascript objects and giving this new array to d3 data. here is the code

App.GraphicsView = Ember.View.extend( {
didInsertElement: function() {
    var svg = d3.select("#svg");
    var data = this.get('controller').get('model').get('content');
    var newData = [];
    for(var i = 0; i < data.length; i++) {
          newData.push(data[i]);
     }
    var graphics = svg.selectAll("rect")
        .data(newData)
        .enter()
        .append("rect");
    graphics.attr("x", function(d, i) {
        return d.get('x');
    })
}

but the data variable ist not realy an array so I cann't iterate over it

3条回答
Anthone
2楼-- · 2020-06-23 08:42

Here is another example : http://jsfiddle.net/2UPLp/16/light/

Requires:

d3.v2.min.js
handlebars-1.0.0.beta.6.js
ember-1.0.pre.min.js
查看更多
▲ chillily
3楼-- · 2020-06-23 09:01

Ember has lots of in-built iterators (Check out the Ember.Enumerable docs). In your case however, simply calling toArray should suffice.

App.GraphicsView = Ember.View.extend({
  didInsertElement: function() {
    var svg = d3.select("#svg");
    var data = this.get('controller.content');
    var newData = data.toArray();
    var graphics = svg.selectAll("rect")
      .data(newData)
      .enter()
      .append("rect");
    graphics.attr("x", function(d, i) {
      return d.get('x');
    })
  }
})

EDIT: Here is a working version of your fiddle http://jsfiddle.net/PkT8x/156/

A couple of things, firstly, you had incompatible versions of Ember and Ember-Data in the fiddle.

Secondly, the FixtureAdapter simulates a remote response by default therefore on didInsertElement the App.Graphic collection was actually empty and it is not until the next runloop that the array was populated with the objects, to fix this, I made Ember re-calculate the d3 object whenever the controller's length changes.

App.GraphicsView = Ember.View.extend({
  graphicsObserver: function() {
    var svg = d3.select("#svg");
    var data = this.get('controller.content');
    var newData = data.toArray();
    var graphics = svg.selectAll("rect")
      .data(newData)
      .enter()
      .append("rect");
    graphics.attr("x", function(d, i) {
      return d.get('x');
    })
  }.observes("controller.length")
})
查看更多
唯我独甜
4楼-- · 2020-06-23 09:05

Here is another approach

https://github.com/sabithpocker/ember-appkit-d3-sample

This particular method is generating paths with d3 and binding it to the svg using Ember. This will result in paths responding to data changes in the app. The example does not use d3 to render the svg, instead it is using d3 API to calculate the path and use it in svg.

查看更多
登录 后发表回答