Copy link to clipboard
Copied
Hello,
in AS3 i used to do this for event bubbling (using evt.target or evt.currentTarget).
mc1.addEventListener(MouseEvent.CLICK, myFunction);
function myFunction(evt:MouseEvent) {
evt.currentTarget.x=300;}
So i write the function only once and added the listener to multiple Targets(symbol instances).
mc2.addEventListener(MouseEvent.CLICK, myFunction);
mc3.addEventListener(MouseEvent.CLICK, myFunction);
How i have to re-write this in JS/HTML5 Canvas? I tried
this.mc1.addEventListener("click", myFunction.bind(this));
function myFunction(evt)
{this.evt.target.x=300;}
But it does not work.
1 Correct answer
sovie4711 wrote
How i have to re-write this in JS/HTML5 Canvas? I triedthis.mc1.addEventListener("click", myFunction.bind(this));
function myFunction(evt)
{this.evt.target.x=300;}
But it does not work.
It's not working because evt is not a property of this, it's an argument being passed into the event handler function. Get rid of the this. in front of it.
Copy link to clipboard
Copied
Write a command to express "evt" or even "this" in the browser console via something like console.log(evt);
What does it spit out?
Copy link to clipboard
Copied
alert(event.target);//[object HTMLCanvasElement]
alert(evt.target) //[Shape (name=null)]
console.log(evt.target); //a {_listeners: null, _captureListeners: null, alpha: 1, cacheCanvas: null, cacheID: 0, …}
console.log(event.target); //<canvas id="canvas" .....">
So i can not grab the "object" in Canvas that is actually clicked?
I ask because i don't like to write the function for every single Symbol (which should do the same thing on Click Event).
Copy link to clipboard
Copied
You can do this. For instance, I have the following code and 2 MCs on the stage:
this.b1.name = "button_one";
this.b1.addEventListener("click", myFunction.bind(this));
this.b2.name = "button_two";
this.b2.addEventListener("click", myFunction.bind(this));
function myFunction(e) {
console.dir(e);
}
Here is what is output:
So I'd go with e.currentTarget.x instead.
Copy link to clipboard
Copied
sovie4711 wrote
How i have to re-write this in JS/HTML5 Canvas? I triedthis.mc1.addEventListener("click", myFunction.bind(this));
function myFunction(evt)
{this.evt.target.x=300;}
But it does not work.
It's not working because evt is not a property of this, it's an argument being passed into the event handler function. Get rid of the this. in front of it.

