Jump to content
Search Community

How to bind animation start to browser event?

BaoLuo test
Moderator Tag

Recommended Posts

Hello everyone!

 

Can anybody explain me why this variant of binding works

document.querySelector('.burger').addEventListener('click', _ => {
  burgerLine.play()
})

and this one

document.querySelector('.burger').addEventListener('click', burgerLine.play)

causes the following error

Quote

gsap.min.js:10 Uncaught TypeError: this.seek is not a function at HTMLButtonElement.play (gsap.min.js:10:19754) 

Link to comment
Share on other sites

Yeah, that's because of how scope works in JavaScript. Consider this class:

class Thing {
  constructor() {
    this._playing = false;
  }
  play() {
    this._playing = true;
  }
}

And now let's do this: 

let a = new Thing();
let b = new Thing();

We've got two "Thing" instances. Now let's do:

document.querySelector("#id").addEventListener("click", a.play);

Technically you're only passing the function ITSELF as the handler. That function definition is shared by ALL instances of "Thing" (a and b in our case). Think of it like a template. When you call a.play(), for example, it calls that method with a very particular scope - "a" is the scope, so "this" inside the function refers to that one particular instance. If you call b.play(), "b" is the scope, so "this" inside the function refers to the b instance. That all happens because you're directly calling the method on the instance, like a.play() and b.play(). But when you set up an event handler and you only pass in the function itself, you lose the scope. So when it calls that method on the event, the scope would be the clicked element itself! So "this" inside play() doesn't refer to "a" at all - it refers to the clicked element. 

 

So yeah, don't do that :) It's a JavaScript thing, not a GSAP thing. 

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...