Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does event listener callback function only work inside function scope?

I'm working on a D3 project that uses an event listener which gets called every few milliseconds to update/animate the position of circles on the screen.

It starts with the function startForces() getting called once to activate the D3 forces and we pass it the circles.

When the callback function (ticked) is positioned outside of the scope of startForces(), the function only seems to called once and the circles appear static on the page. (SEE TOP CODE CHUNK)

But, when the callback function (ticked) is positioned inside the scope of startForces(), everything works as expected and the circles appear animated. (BOTTOM CODE CHUNK)

I'm trying to understand why javascript is working this way. Why does the top code not work, and the bottom code work?

TL:DR

NOT-WORKING CODE

var ticked = function(circles){
   circles.attr('cx', function(d) { return d.x })
   .attr('cy', function(d) { return d.y })
}

var startForces = function(data, circles) {
  simulation.nodes(data)
  .on('tick', ticked(circles))
}

=====

WORKING CODE

    var startForces = function(data, circles) {
      simulation.nodes(data)
      .on('tick', ticked)

    function ticked(){
      circles.attr('cx', function(d) { return d.x })
      .attr('cy', function(d) { return d.y })
    }
   }

Why the difference?

like image 507
Starcat Avatar asked Sep 06 '26 09:09

Starcat


1 Answers

It actually has nothing to do with the position of the functions at all.

When you do this:

.on('tick', ticked(circles))

You immediately call ticked right as you create the on listener. Then, you assign the callback for tick to be the result of calling ticked with circles, which is undefined.

When you do this:

.on('tick', ticked)

You assign the callback to be the ticked function, which is what you want.

like image 168
thedayturns Avatar answered Sep 07 '26 22:09

thedayturns



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!