tags:

views:

106

answers:

2

When a Flex component moves directly, so that its x and y properties change, then a "move" event is dispatched on the component. That's all fine.

However, a component may also move as a result of its parent component moving — or its parent moving, and so on. Now when a parent component moves, its children just "move along" without any properties changing or move events being dispatched on the children. Still, the children are moving on the screen. So how can you detect this kind of generalized movement?

+1  A: 

One workaround is to capture all move events in the application:

Application.application.addEventListener
  (MoveEvent.MOVE, handleMove, true, 0, true);

The third argument is required because move events do not bubble, and so instead have to be captured. The fourth argument is unimportant, and the fifth argument turns on weak references, which is a good idea in this case because we are creating a global reference from Application.application to handleMove — a recipe for memory leaks.

Of course, this will fire too often (once each time anything whatsoever in the application moves), and in a large application could lead to performance problems. If you know that there is some component higher up in the hierarchy that’s sure to stay still, you can put the listener at that point instead of globally, which could reduce the problem.

Still, it would be nice to have a cleaner way to solve this.

Daniel Brockman
A: 

Well, you've already suggested the most general solution, but I think it's possible for the child to go through parents/grandparents until it reaches one that is stationary (set by some dynamic property you set), at least this would save you some trouble in figuring out which parent handles which child.

private function addHandlerToStationaryParent(handler:function):void
{
    var currentParent:DisplayObjectContainer = parent;
    while(currentParent != null)
    {
        if(currentParent["stationary"] == true)
        {
             currentParent.addEventListener(MoveEvent.MOVE, handler);
             return;
        }
    }
}

I guess it would be your preference as to whether or not this would be a better solution.

CookieOfFortune
You’d still have to pass true as the third argument to addEventListener to enable capturing, though. Also, it would be better to add the event listener to an immediate child of the stationary ancestor — otherwise you risk catching events from irrelevant children of the stationary ancestor.
Daniel Brockman
Well, I was just demonstrating a point.
CookieOfFortune