Re: click event not registering on sprite
Ok, the attached code below should answer your original question. The problem
was that Shape doesn?t inherit from InteractiveObject. I was under the
assumption that if a subclass inherits from EventDispatcher it would be
interactive. So in your last post, your conclusion was partial right; the
stage was listening as expected but descendant (Shape) was not. Now we know.
So I just added the shape instance to a sprite instance and it works. I also
have a listener for Event.ADDED_TO_STAGE. So when ClickTest is actually
attached to the stage, then listen for the Mouse.CLICK. Listening for
ADDED_TO_STAGE event may be redundant here. I don?t have the experience yet to
know when it is needed.
package
{
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.EventPhase;
import flash.events.MouseEvent;
public class ClickTest extends Sprite
{
public function ClickTest()
{
super();
this.drawBox();
addEventListener(Event.ADDED_TO_STAGE, addedToStage);
}
private function addedToStage(e:Event):void
{
trace("I am added to the display list. "+e.target);
this.stage.addEventListener(MouseEvent.CLICK, clickHandler);
}
private function clickHandler(e:MouseEvent):void
{
trace(e.eventPhase);
if(e.eventPhase != EventPhase.AT_TARGET)
{
trace("Mouse clicked at: " + e.localX + ", "
+ e.localY);
trace("Target of the event: " + e.target);
}
}
private function drawBox():void
{
var boxContainer:Sprite = new Sprite();
var box:Shape = new Shape();
box.graphics.lineStyle(2, 0x990000, .75);
box.graphics.beginFill(0xFF0000, 0.5);
box.graphics.drawRect(0,0,100,100);
boxContainer.addChild( box );
addChild( boxContainer );
}
}
}
|