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/
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With