Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3's .call() returning "Cannot read property 'apply' of undefined"

The following code creates three draggable circles based on the x, y values of an object array:

JS:

  var obj = this

  data = [{
    'x': 100,
    'y': 100
  }, {
    'x': 200,
    'y': 200
  }, {
    'x': 300,
    'y': 300
  }]

  var circle = d3.select("svg")
    .selectAll("g")
    .data(data)
    .enter().append("g")
    .attr('class', 'point')
    .attr('transform', function(d) {
      return 'translate(' + d.x + ',' + d.y + ')'
    })
    .call(drag)

  var drag = d3.behavior.drag().on('drag', function() {
    dragMove(this, obj, 'points')
  })

  //// Actions

  circle.append('circle')

  // Methods

  function setPoints(obj, prop) {
    obj[prop] = []
    var k = 0
    d3.selectAll('.point')
      .each(function() {
        var c = d3.select(this)
        var cX = d3.transform(c.attr('transform')).translate[0]
        var cY = d3.transform(c.attr('transform')).translate[1]
        obj[prop].push({
          x: cX,
          y: cY,
          index: k++
        })
      })
  }

  function dragMove(circle, obj, prop) {
    var x = d3.event.x
    var y = d3.event.y
    setPoints(obj, prop)
    d3.select(circle).attr('transform', 'translate(' + x + ',' + y + ')')
    $scope.$apply()
  }

HTML:

<div id="points">
  <svg width='400' height='400'></svg>
</div>

For some reason, call(drag) throws Cannot read property 'apply' of undefined

Why is this? And how to fix it?

https://jsfiddle.net/alexcheninfo/du1a55a2/1/

like image 867
alexchenco Avatar asked Jan 25 '16 06:01

alexchenco


1 Answers

You have to define the variable before you use it

var drag = d3.behavior.drag().on('drag', function() {
      dragMove(this, obj, 'points')
});

var circle = d3.select("svg")
      .selectAll("g")
      .data(data)
      .enter().append("g")
      .attr('class', 'point')
      .attr('transform', function(d) {

          return 'translate(' + d.x + ',' + d.y + ')'

       }).call(drag);

FIDDLE

right now you're passing undefined as the this value to call()

like image 81
adeneo Avatar answered Oct 11 '22 11:10

adeneo