2 Replies Latest reply on May 5, 2016 9:22 AM by ClayUUID

    Question about createjs syntax in Animate

    sofiaw46477135

      Hi all,

       

      I'm a beginner in Animate an I have a question about the createjs syntax.

       

      This code works:

       

      this.mybutton.addEventListener("click", buttonaction.bind(this));

      function buttonaction()

      {

        this.gotoAndPlay(10);

      }

       

      But this code is not working I want to know why:

       

      this.mybutton.addEventListener("click", buttonaction);

      function buttonaction()

      {

        this.gotoAndPlay(10);

      }

       

      can someone help me please?

        • 1. Re: Question about createjs syntax in Animate
          Colin Holgate MVP & Adobe Community Professional

          In Javascript, 'this' inside a function refers to the function itself, and the function is not a movieclip. If you want the timeline to go to frame 10 you can do that in a couple of ways. Here's one way:

           

          var self = this;

          this.mybutton.addEventListener("click", buttonaction);

          function buttonaction()

          {

            self.gotoAndPlay(10);

          }

           

          That would put the timeline's 'this' value into the 'self' variable, so that inside the function it will cause the timeline to go to frame 10. The other way is to use 'bind', which will make the function use the timeline's value for 'this'.

          • 2. Re: Question about createjs syntax in Animate
            ClayUUID Adobe Community Professional

            Colin Holgate wrote:

             

            In Javascript, 'this' inside a function refers to the function itself, and the function is not a movieclip.

            That's inaccurate. "this" references the current context (not to be confused with the current scope, which is indeed the current function).

             

            Sofia, the reason your second code example isn't working is because JavaScript event handlers by default execute in the global context (and scope), meaning "this" references the top-level window object. This can be worked around either by storing a global reference to the local context of interest, which can then be accessed by the event handler, or by using the bind() function, which "binds" the event handler to a specific context.

             

            Colin's example above wouldn't work as written because "var self" declares self into the local frame-level scope, which would be inaccessible to the event handler code.