Search code examples
javascripttween

Reference in callback function


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

   }    
}

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?