【问题标题】:How to pass values into anonymous function that is triggered by an event?如何将值传递给由事件触发的匿名函数?
【发布时间】:2013-09-14 13:29:33
【问题描述】:

我在 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') 为什么?我该如何解决这个问题?

【问题讨论】:

    标签: javascript function events kineticjs


    【解决方案1】:

    尝试使用 closure 来捕获当前的 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 等于 linkItemsLen,在您的 eat 数组之外 => eat[i] 返回 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]
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-15
      相关资源
      最近更新 更多