Jump to content
Search Community

Variable is undefined after calling onUpdate function

charne test
Moderator Tag

Go to solution Solved by GreenSock,

Recommended Posts

I have GSAP.to where I am going to get a number from 1 - 100 based on the tween. On every tick I have an onUpdate for running a function on each calculation (which will get passed the percent based on the tween). Whenever updateFunction()  runs from onUpdate, I always get myPercent = undefined. If I run updateFunction() directly, I get myPercent = 1. If I try and reference anything else in updateFunction() everything is undefined or it can't find any other functions.

 

Is onUpdate creating an instance of something? I can't figure out how to access the function directly. I hope my explanation makes sense. Appreciate the help.

This is my setup:

import GSAP from "gsap";

export default class Controls {
  constructor() {
    this.experience = new Experience();
    this.scene1(); 
   
  }

    scene1(){
        this.myPercent = 1
        this.theTimeline = GSAP.to(this, {
            duration: 1,
            onUpdate: this.updateFunction,
        }); 
        this.updateFunction(); // Added this on the end to test - when run from here, I do get myPercent = 1
    }

    updateFunction() {
        console.log(this.myPercent)
        //output for every tick from GSAP onUpdate: myPercent = undefined
    }

    update() {}
    
}

 

 

Link to comment
Share on other sites

  • Solution

Welcome to the forums, @charne

 

That's a scoping issue in your code. By default, "this" inside a callback refers to the Tween instance but your code assumes it is the Controls instance. 

 

There are several ways to fix this, but I would recommend just using an arrow function because scope doesn't change on an arrow function: 

onUpdate: () => this.updateFunction(),

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...