如何将值传递到由事件触发的匿名函数中

How to pass values into anonymous function that is triggered by an event?

本文关键字:函数 事件 值传      更新时间:2023-09-26

我在Kinetic中遵循代码.js:

    function pacmanMove(x, y , duration, bate, color) {
        var tween = new Kinetic.Tween({
            node: group,
            duration: duration,
            x: x,
            y: y,
            onFinish: function() {
                changeColor(color);
                window[bate].remove();
            }
        });
        return tween;
    }
    var eat = [];
    for(var i = 0; i < linkItemsLen; i++) {
        eat.push(pacmanMove(linkItems[i][2], 65, 1, linkItems[i][0], linkItems[i][4]));
        window[linkItems[i][0]].on('mouseover', function() {
            this.tween = eat[i];
            this.tween.play();
        });
    }

正在尝试将动态创建的补间传递到鼠标悬停事件中,但补间始终未定义,因此当触发事件时,我收到一条错误消息TypeError: 'undefined' is not an object (evaluating 'this.tween.play')为什么?我该如何解决这个问题?

尝试使用闭包来捕获当前i,并改用var来创建私有变量。

for(var i = 0; i < linkItemsLen; i++) {
        eat.push(pacmanMove(linkItems[i][2], 65, 1, linkItems[i][0], linkItems[i][4]));
        window[linkItems[i][0]].on('mouseover', (function(index) { //create closure to capture current index.
           return function(){
              //Use var instead
              var tween = eat[index];
              tween.play();
            }
        })(i));
    }

由于您在循环中附加事件处理程序,因此在循环结束时,i等于eat数组 => eat[i] 之外的linkItemsLen 返回undefined 。所有事件处理程序都会丢失当前i

使用相同的技术,您也可以将补间直接传递给函数:

for(var i = 0; i < linkItemsLen; i++) {
            eat.push(pacmanMove(linkItems[i][2], 65, 1, linkItems[i][0], linkItems[i][4]));
            window[linkItems[i][0]].on('mouseover', (function(tween) { //create closure to capture current eat[i].
               return function(){
                  tween.play();
                }
            })(eat[i]));//Pass the current eat[i]
        }