简体   繁体   中英

Redefining nested function's variable from each call to parent in JavaScript?

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.

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);

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM