Flex executing a function on another view

2019-03-04 13:35发布

问题:

I have a headerbar.mxml that is displayed when user swipes_down in my app. The headerbar.mxml contains a button component I want to run an erase() in the main application window. The main application is a drawing app that contains an erase(). I just don't know how to call a function from another mxml view file. I thought it would be something like click="{mainwindow.drawPanel.erase()}";

EDIT:

protected function onColorChange(event:List):void{
                appHome.drawArea.erase();
            }

回答1:

To run a function in another view (AKA Component) It depends largely on the architecture. It sounds like you want to run a function in your parent. In which case the 'encapsulation proper' method is to dispatch an event from component1; listen for the event in component1s parent; and execute the function from the event listener.

So, somewhere in headerbar's parent, add the event listener:

headerbarInstance.addEventListener('parentDoSomething', onHeaderBarToldMeTo);

I'd probably add this in the constructor if an ActionSCript 3 component, or in a preinitialize event handler if an MXML Component. The 'parent' component will also need the listener function:

protected function onHeaderBarToldMeTo(event:Event):void{
  erase();
}

When the clicks the button component in headerbar.mxml and this fires off a click event handler inside of headerbar, which needs to dispatch the event, like this:

protected function onButtonInheaderbarClick(Event:Event):void{
 dispatchEvent(new Event('parentDoSomething'));
}

And everything should magically work. You may have to bubble the event if the function is not inside a direct child of the parent.

If you don't care about encapsulation, you can also just access the parent directly. So your header bar component would do this:

parent.erase();

It's simple and straight forward, and should work, but is considered horribly bad practice from a maintenance stand point.