Ad

Why Aren't The Changes To My Variable Being Visible Outside Of This Function?

- 1 answer

The following code is a D3 snipped put inside a VueJS instance. The snippet creates circles and lets you drag them.

new Vue({
  el: 'body',

  data: {
    x: '',
    y: ''
  },

  computed: {
    pos: function () {
      function click() {

        var point = d3.mouse(this),
          p = { x: point[0], y: point[1] }

        svg.append('circle')
          .attr('transform', 'translate(' + p.x + ',' + p.y + ')')
          .attr('r', '5')
          .attr('class', 'dot')
          .style('cursor', 'pointer')
          .call(drag)

        var dots = d3.selectAll(".dot")

        var svg = d3.select('body').append('svg')
          .attr('width', 400)
          .attr('height', 400)
          .on('click', click)

        var drag = d3.behavior.drag()
          .on('drag', dragmove)

        function dragmove(d) {
          var x = d3.event.x
          var y = d3.event.y
          d3.select(this).attr('transform', 'translate(' + x + ',' + y + ')')
          this.x = x
          console.log('x:', this.x)
      }

    console.log('x:', this.x)
    }
  },

  ready: function () {
  }
})

Now, I'm trying to get position x of the dragged circles. The first console.log('x:', this.x) logs the position: x: 190. But the second long, the one outside of the dragmove() function doesn't log anything.

How can I make the second console.log log the value of this.x?

Here's the JSFiddle: https://jsfiddle.net/alexcheninfo/unejge3k/1

Ad

Answer

If you want to access the x outside of the dragmove function the nyou have to define the x in the outer scope.

var x, y;

function dragmove(d) {
          x = d3.event.x
          y = d3.event.y
          d3.select(this).attr('transform', 'translate(' + x + ',' + y + ')')
          this.x = x
          console.log('x:', this.x)
      }
console.log('x:', this.x)

But I really really don't recommend this method.

Since you want the translation of the circle, you can do it like this.

var c = svg.append('circle')
          .attr('transform', 'translate(' + p.x + ',' + p.y + ')')
          .attr('r', '5')
          .attr('class', 'dot')
          .style('cursor', 'pointer')
          .call(drag)
var trans = d3.transform(c.attr('transform')).transalte;

var tx = trans[0];
var ty = trans[1];

Hope this will help you.

Ad
source: stackoverflow.com
Ad