1

Recently I started learning about JS, and I got stuck in the following issue:

I am trying to call a function "draw_point" when a "mousemove" event happens.

When trying the following, the code works as expected (the function gets called):

    svg.on('mousemove', draw_point(true));

But when replacing the caller function like this, it stops working and I don't get any error messages to troubelshoot.

    svg.on('mousemove', function () {
        draw_point;
    });

Any explanation of what is going on?

  • 1
    In the first case you *execute* `drawPoint` and pass in the parameter `true`. Note that unless that returns a function, it will just be executed *once* and it happens *immediately* - it will not be assigned as a handler. In the second case, you create a function but never execute `drawPoint`. It's valid code to mention the function reference there but it does nothing at all, since it's not invoked. – VLAZ Jun 28 '20 at 18:24

1 Answers1

1

Both examples are wrong, but for different reasons. In the first, you're calling the functiondraw_point immediately and passing its return value to the .on call. In the second, you're creating an anonymous function that wraps draw_point, but you're not calling draw_point. This is legal because javascript allows empty statements like myVar; or 3;.

What you want to do is pass the function draw_point, but not call it. It will be called when the handler runs:

svg.on('mousemove', draw_point);
frodo2975
  • 10,340
  • 3
  • 34
  • 41
  • Many thanks! Then what would be the syntax to run multiple functions when the 'mousemove' is called? I was hoping to be something like this, but I now I am pretty sure it won't work svg.on('mousemove', function () { draw_point; draw_line; }); – Anonymous1321423 Jun 28 '20 at 18:27
  • You're welcome! What you've suggested will also work, you just need to put parenthesis to actually call the functions, like `function () { draw_point(); draw_line(); }` – frodo2975 Jun 28 '20 at 19:06