views:

1574

answers:

4

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?

+2  A: 
oneCent.addEventListener(MouseEvent.MOUSE_MOVE, dragIt);
...

function dragIt(event:MouseEvent):void
{
...
Scott Evernden
How do I pass in the second parameter in the dragIt method call?
James Sun
Use the id instead of a new variable. The id will be available via event.target.id .
defmeta
A: 

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.

zenazn
Why is it better to use an anonymous function? You can not remove the event listener with an anomymous function.
ForYourOwnGood
Depending on the circumstance, using anonymous event handlers can lead to memory leaks. The object being observed (oneCent) is now referenced by the event subsystem, but as ForYourOwnGood states, this handler now cannot be removed.
Matt Dillard
You can use weak links (it's one of the parameters--forget which) to work around this. But yeah--I didn't think about that :)
zenazn
+1  A: 

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.

joshtynjala
+2  A: 

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

Iain