2 Replies Latest reply on Sep 4, 2017 4:16 PM by RandomlyFish

    I can't assign a value to instance inside a function... why?


      Hi, I can't understand... I have:


      this.perc = 0;

      this.seekbar_mc.progressbar_mc.scaleX = this.perc;


      video_mc.ontimeupdate = function() {onTrackedVideoFrame()};


      function onTrackedVideoFrame() {


          this.perc = ((video_mc.currentTime / video_mc.duration));

         javascript: console.log(this.perc);


          this.seekbar_mc.progressbar_mc.scaleX =  this.perc;  // it doesn't work!!



      why I can't assign the value to seekbar_mc.progressbar_mc.scaleX, I try also without this., but nothing...

        • 1. Re: I can't assign a value to instance inside a function... why?
          ClayUUID Adobe Community Professional

          It's not working because in event handlers, by default "this" is set to the window context, not the object that triggered the event. You have to either bind the event handler context, or set a global variable equivalent to the context you want that the event handler can then access.


          Also, unless you plan on accessing "perc" from any other frames, you don't need to define it as a class property. You can just make it a regular local variable. The event handler will be able to see it because it's defined in the same lexical scope.


          There's also some weird and redundant syntax in your JavaScript code, like defining an anonymous function that does nothing but call another function, double parentheses around a division operation, and that "javascript:" line label.


          This should work:


          var perc = 0;

          this.seekbar_mc.progressbar_mc.scaleX = perc;


          video_mc.ontimeupdate = onTrackedVideoFrame.bind(this);


          function onTrackedVideoFrame() {

              perc = video_mc.currentTime / video_mc.duration;


              this.seekbar_mc.progressbar_mc.scaleX =  perc;



          But wait... "perc" is only ever updated immediately before being used to scale the progress bar. Is there any real reason for this variable to exist at all? It seems like this should work just as well:



          video_mc.ontimeupdate = onTrackedVideoFrame.bind(this);


          function onTrackedVideoFrame() {

              this.seekbar_mc.progressbar_mc.scaleX =  video_mc.currentTime / video_mc.duration;


          • 2. Re: I can't assign a value to instance inside a function... why?
            RandomlyFish Level 3

            Like ClayUUID explained, "this" does not reference the same thing inside the function scope as it does outside it. So personally I like to create a variable called "main" to keep a reference of "this" and then just use that variable instead of "this".