I seem to have trouble removing addEventListeners when I jump between frames. When I jump back and forth, the addEventListeners still seem to stack up:
Frame 1 code:
this.stop();
this.arrowForward_btn.addEventListener("click", arrow_btnClickForward.bind(this));
function arrow_btnClickForward() {
this.arrowForward_btn.removeEventListener("click", arrow_btnClickForward.bind(this));
console.log("went forward");
alert("alert: went forward!");
this.gotoAndStop(1);
}
Frame 2 code:
this.arrowBack_btn.addEventListener("click", arrow_btnClickBack.bind(this));
function arrow_btnClickBack() {
this.arrowBack_btn.removeEventListener("click", arrow_btnClickBack.bind(this));
console.log("went back!");
alert("alert: went back!");
this.gotoAndStop(0);
}
How do I remove the addEventListeners so that they don't stack up?
Update: Was told about evt.remove(); so I used that in my codes and it works:
Frame 1 code:
this.stop();
this.arrowForward_btn.addEventListener("click", arrow_btnClickForward.bind(this));
function arrow_btnClickForward() {
console.log("went forward");
alert("alert: went forward!");
this.gotoAndStop(1);
evt.remove();
}
Frame 2 code:
this.arrowBack_btn.addEventListener("click", arrow_btnClickBack.bind(this));
function arrow_btnClickBack(evt) {
console.log("went back!");
alert("alert: went back!");
this.gotoAndStop(0);
evt.remove();
}
Your update is better, but it might help to explain a few things:
bind()
, it generates a new unique closure. Every time.Note that evt.remove()
should work for you, but in your first example (frame 1 code), the event handler doesn't have an evt
param.
A few things in CreateJS might help:
on()
method is a shortcut for addEventListener, which helps you do things like pass scopethis.arrowForward_btn.on("click", arrow_btnClickForward, this);
once
parameter, so if you know your event will fire one time, it can get auto-removed.this.arrowForward_btn.on("click", arrow_btnClickForward, this, true);
on()
returns the generated closure. You can use off()
to remove easily.var handler = this.arrowForward_btn.on("click", arrow_btnClickForward, this);
// later
this.arrowForward.off("click", handler);
Hopefully that gives you a better understanding of event handlers in CreateJS, and some combination of that will work.
--
It might also be helpful to know that you can write all your code in the first frame, since CreateJS bootstraps instances in every frame when the movieclip is initialized. So arrowBack_btn
will exist in frame 1 as well. You could just add the code once, and ensure it only run
if (this.inited == false) {
this.inited = true;
this.arrowForward_btn.on("click", arrow_btnClickForward, this);
this.arrowBack_btn.on("click", arrow_btnClickBack, this);
function arrow_btnClickForward() {
console.log("went forward");
alert("alert: went forward!");
this.gotoAndStop(1);
}
function arrow_btnClickBack(evt) {
console.log("went back!");
alert("alert: went back!");
this.gotoAndStop(0);
}
}
I didn't test this, but it should work :D