将数组传递给tweenjs将无法正常工作

时间:2014-08-05 19:25:05

标签: javascript closures tween.js

我想用tween.js为多个屏幕对象设置动画。

对象以数组形式组织,我想将每个单独的元素传递给补间函数,该函数大致如下所示:http://jsfiddle.net/8L9Dz/

var target1 = document.getElementById( 'target1' );
var target2 = document.getElementById( 'target2' );

targets.push(target1);
targets.push(target2);

for(var i = 0; i < 2;i++ ){
    var tween = new TWEEN.Tween( targets[i].dataset )  // i'th element
        .to( { rotation: 360, y: 300 }, 750 )
        .easing( TWEEN.Easing.Cubic.InOut )
        .onUpdate( function() {
            updateBox( targets[i], this );
        })
        .start();
}

当我在本地运行代码时,firefox告诉我&#34;框未定义&#34; - 这对应于updateBox(...)

中的第一行

我想这与函数的关闭有某种关系,但我不是JavaScript专家 - 有谁知道?

1 个答案:

答案 0 :(得分:1)

尝试按如下方式重写代码以避免循环变量的闭包:

var tween = new TWEEN.Tween( targets[i].dataset )  // i'th element
    .to( { rotation: 360, y: 300 }, 750 )
    .easing( TWEEN.Easing.Cubic.InOut )
    .onUpdate( (function(id, ctx) { 
        return updateBox(targets[id], ctx); 
    })(i, this) )
    .start();

更新

onUpdate应该接收一个函数作为参数,我错过了。请尝试如下:

...
.onUpdate( (function(id, ctx) { 
        return function() { updateBox(targets[id], ctx) }; 
    })(i, this) )
...

UPDATE2:

this不应传递给onUpdate,请尝试以下操作:

var tween = new TWEEN.Tween( targets[i].dataset )  // i'th element
              .to( { rotation: 360, y: 300 }, 750 )
              .repeat(Infinity)
              .easing( TWEEN.Easing.Cubic.InOut )
              .onUpdate( (function(id) { 
                return function () { updateBox(targets[id], this); };
              })(i) )
              .start();

注意:在你的.zip中你没有在Tween构造函数中使用目标[i] .dataset,注意