0

I've got a nested function inside another JavaScript function; the nested function accepts a variable that is passed to the parent. The first time I call the parent, all variables are set correctly. However any subsequent times that I call the parent, the nested function doesn't apply the new variable that was passed to the parent (instead it persists the variable from the first call).

For example:

myFunc: function(path, points) {
   var onDrag      = function(e) {

       // This is the variable I want redefined each time I 
       // call myFunc with new points
       console.log('points: ', points);

    },
    onDragStart   = function(e) {
      window.addEventListener('mousemove', onDrag);
    };

    this.el.addEventListener('mousedown', onDragStart);

    return this;
}

The above is a stripped-down version of my method. I call myFunc when I create my element, and as you can see onDrag gets called on mousedown on the element. But, I also call myFunc directly at several points later in the script, passing it new variables for path and points, expecting onDrag's references to these variables to update.

However, this isn't happening, instead onDrag is persisting the points variable from the first time I called it.

How can I have my nested function update it's variables each time I call its parent?

What I've tried:

I've tried passing points as an argument to the onDrag, like this:

onDrag = function(e, points) { }

I've tried redefining a variable inside the onDrag scope, like this:

onDrag = function(e) { var pts = points; }

I've tried not defining the function in a variable, like this:

function onDrag(e) { }

But none of these things has worked.

Nick Budden
  • 621
  • 9
  • 20

2 Answers2

1

If you call the "myFunc" again it will again attach add new eventListner on window object. You need to first remove previously attached event from window.

window.removeEventListener('mousemove', onDrag, false);

Sandeeproop
  • 1,756
  • 1
  • 12
  • 18
0

you need to pass the arguments to onDrag at the time that you invoke it.

myFunc: function(path, points) {
   var onDrag      =  function(e, points) {

        // This is the variable I want redefined each time I 
        // call myFunc with new points
        console.log('points: ', points);


    },

    onDragStart   = function(e, points) {
      window.addEventListener('mousemove', onDrag(e, points));
    };

    this.el.addEventListener('mousedown', onDragStart(e, points));

    return this;
}
adrichman
  • 1,215
  • 10
  • 17
  • To pass arguments, I've got to write it like this: window.addEventListener('mousemove', function(e) { onDrag(e, points); }); Unfortunately that means I wouldn't be able to unbind the event later: http://stackoverflow.com/a/256763/740836 – Nick Budden Apr 16 '14 at 06:54