In Adobe AnimateCC using CreateJS I have an mc on frame one called disclaimer_btn
, and an mc on frame one called discTxt
. I want to be able to mouseover disclaimer_btn
and gotoAndStop on a frame label in discTxt
. Round about frame 150 I try to do the mouseover and it's not working. If I use an alert box in my function, that works.
The error is Uncaught TypeError: Cannot read property 'bind' of undefined
and in the code it points to here .bind(this));
If I remove this.discTxt
from before this.discTxt.fl_MouseOverHandler.bind(this));
I get the error Uncaught ReferenceError: fl_MouseOverHandler is not defined
.
I have read this SO post and this one and those solutions are not working for me in this case.
I get this is a problem of scope, what am I doing wrong here?
var frequency = 3;
stage.enableMouseOver(frequency);
this.disclaimer_btn.addEventListener("mouseover", this.discTxt.fl_MouseOverHandler.bind(this));
this.fl_MouseOverHandler = function()
{
this.discTxt.gotoAndStop("on");
}
This is just a problem with the order. Because you have to define the function as a variable on this
, the function definition is not 'hoisted". Hoisted functions get defined first, no matter the order they are defined in the code.
// Hoisted
function myFunction() {}
// Not hoisted
var myFunction = function() {}
this.myFunction = function() {}
In the second example, the variable itself is defined, but it will be null until the line where you set it. You can fix this by moving the addEventListener
to below that line so it is called after the function is defined.
Alternatively, change to a hosted method, and bind that:
btn.addEventListener("click", myFunction.bind(this));
function myFunction() {}
You can also use on
, which is a CreateJS function replacement for addEventListener
, which has some syntactic sugar, such as a scope parameter.
btn.on("click", myFunction, this);
Lastly, if you do define the function using this
, ensure you pass the right value. In your example, you define the function on this
, but pass it as a property of this.discTxt
. Unless this.discTxt
is another MovieClip, and the function is defined there instead, you will be passing null.
TLDR:
this
, then move it below the `addEventListenerfunction myFunction()
, and bind it.