Copy link to clipboard
Copied
Please can someone explain how I can access a "clip" scoped variable within a function associated with a button click
In the example code below I set a "clip" variable this.myVar = "Paul
Within a function called whatIsMyVariable - I am able to access the value of this clip variable
However in a function associated with the button click listener I am not able to access it.
I am assuming it is some sort of scoping issue but not sure how to resolve it. I would appreciate someone explaining this.
Is it possible to access the myVar variable value within this clickTestButton function?
this.myVar = "Paul";
alert ("this.myVar = " + this.myVar);
this.whatIsMyVariable = function()
{
alert ("function this.myVar = " + this.myVar);
}
this.whatIsMyVariable();
this.clickTestButton = function()
{
alert ("this.myVar = " + this.myVar);
}
this.myTestButton.addEventListener("click", this.clickTestButton);
JavaScript event handlers execute in the global (window) scope. The two usual ways to address this are to put any variables you need the handler to access in the global scope as well, or use bind() to attach the event handler to a specific scope.
this.myTestButton.addEventListener("click", this.clickTestButton.bind(this));
Note that if you use bind(), and you'll need to remove the event listener later, you must save the reference returned by bind(), because it generates a unique function instance
...Copy link to clipboard
Copied
JavaScript event handlers execute in the global (window) scope. The two usual ways to address this are to put any variables you need the handler to access in the global scope as well, or use bind() to attach the event handler to a specific scope.
this.myTestButton.addEventListener("click", this.clickTestButton.bind(this));
Note that if you use bind(), and you'll need to remove the event listener later, you must save the reference returned by bind(), because it generates a unique function instance.
javascript - Removing event listener which was added with bind - Stack Overflow
Copy link to clipboard
Copied
Thank you. I have implemented the bind solution. My next question would have been how to remove the event listener as I noticed it was firing multiple times if I revisited the keyframe where the listener is added. I have therefore created a reference so I am able to remove it. It seems to be happy to call the removeEventListener the first time too without any error.
this.clickMyButton = function()
{
// Code goes here
}
this.myButton.removeEventListener("click", this.clickListener);
this.clickListener = this.clickMyButton.bind(this)
this.myButton.addEventListener("click", this.clickListener);
Copy link to clipboard
Copied
The more self-documenting approach would be this:
if (!this.myButton.hasEventListener("click")) {
this.clickListener = this.clickMyButton.bind(this);
this.myButton.addEventListener("click", this.clickListener);
}