Question

I'm trying to pass an object through a callback function onUpdateTween( groups[i], this ); but it doesn't give me the correct object. It only gives me the last object from the groups array. How can I solve this?

function transform( duration ) {    
   for ( var i = 0; i < groups.length ; i ++ ) {                    

      new TWEEN.Tween(object.rotation)
      .to( rot , duration )
      .easing( TWEEN.Easing.Exponential.InOut ) 
      .onUpdate( function() {
                   onUpdateTween( groups[i], this );
                 })
      .start();                 

   }    
}
Was it helpful?

Solution

Simply call a function in your loop:

function transform( duration ) {    
    for ( var i = 0; i < groups.length; i ++ ) {
        transformGroup( groups[i] );
    }

    function transformGroup( group ) {
        new TWEEN.Tween(object.rotation)
            .to( rot, duration )
            .easing( TWEEN.Easing.Exponential.InOut ) 
            .onUpdate( function() {
                onUpdateTween( group, this );
            })
            .start();                 
    }    
}

Each time you call the transformOne() function, it creates a closure which holds the group parameter so the onUpdate() handler gets the correct group.

Or another way to do the same thing:

function transform( duration ) {    
    for ( var i = 0; i < groups.length; i ++ ) {
        transformGroup( groups[i], duration );
    }
}

function transformGroup( group, duration ) {
    new TWEEN.Tween(object.rotation)
        .to( rot, duration )
        .easing( TWEEN.Easing.Exponential.InOut ) 
        .onUpdate( function() {
            onUpdateTween( group, this );
        })
        .start();                 
}    

Either way would work just as well.

Is this getting the value you need there, or is that a problem too?

OTHER TIPS

You should create a local scope in order to encapsulate this variable :

function transform( duration ) {    
   for ( var i = 0; i < groups.length ; i ++ ) {                    

      new TWEEN.Tween(object.rotation)
          .to( rot , duration )
          .easing( TWEEN.Easing.Exponential.InOut ) 
          .onUpdate( updateTween(i, this) )
          .start();                 

   }    
}

function updateTween(index, object) {
    return function() {
        onUpdateTween( groups[index], object );
    }
}
function transform( duration ) {    
   for ( var i = 0; i < groups.length ; i ++ ) {                    
      with({i:i}) {
          new TWEEN.Tween(object.rotation)
          .to( rot , duration )
          .easing( TWEEN.Easing.Exponential.InOut ) 
          .onUpdate( function() {
                       onUpdateTween( groups[i], this );
                     })
          .start();                 

       }
   }
}

:D

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top