James Sun
James Sun

Reputation: 1461

Flex: How to assign method to Image.MouseMove event programmatically?

I understand how to declaratively assign a method to be called when an Image receives a MouseMove event.

    <mx:Image 
        id="oneCent"
        mouseMove="dragIt(event, 1);"
    />

How do I do this programmatically in Flex/AS3?

EDIT: Thanks for the comments. Here's what I have so far:

          myImage = new Image();
            myImage.id = "oneCent";
            myImage.addEventListener(MouseEvent.MOUSE_MOVE, dragIt);

The code snippet above assigns the dragIt method to the MOUSE_MOVE event for myImage. So far, so good. How do I pass in the 2nd parameter to the call to dragIt?

Upvotes: 0

Views: 2627

Answers (4)

Iain
Iain

Reputation: 9452

You can't pass the second param directly - so add it to myImage:

myImage = new Image();
myImage.id = "oneCent";
myImage.num = 1;
myImage.addEventListener(MouseEvent.MOUSE_MOVE, dragIt);

Then in the dragit function:

function dragIt(event:MouseEvent):void {
    trace("PARAM =", event.target.num, event.target.id);
}

Where event.target automatically becomes a reference to the image

Upvotes: 2

Josh Tynjala
Josh Tynjala

Reputation: 5242

You can't pass extra arguments to event handlers. Behind the scenes, the Flex compiler is generating code that looks something like this:

private function generatedMouseMoveHandler(event:MouseEvent):void
{
    dragIt(event, 1);
}

Any event handler created in MXML will be wrapped like that. That's why you can refer to a variable named event.

Upvotes: 1

zenazn
zenazn

Reputation: 14345

Scott's got it, although it's even better (and cleaner!) to use an anonymous function:

oneCent.addEventListener(MouseEvent.MOUSE_MOVE, function(e:MouseEvent):void{
    ...
});

Which is better if you're not gonna use dragIt() later in your code.

Upvotes: 0

Scott Evernden
Scott Evernden

Reputation: 39986

oneCent.addEventListener(MouseEvent.MOUSE_MOVE, dragIt);
...

function dragIt(event:MouseEvent):void
{
...

Upvotes: 2

Related Questions