0

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 Answer 1

2

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.

3
  • Thanks I understand how to do it now if I'm just referencing a functon in another view, however what I forgot to mention is that the erase() is in a drawArea object I instantiate in my main appview. So I need to run the erase() on the object in my other view. Please see my edit. That is what I'm trying to do now. Jun 5, 2011 at 19:56
  • @Casey Wylde if 'erase()' is a public method on a child of the view; then once the event bubbles up; instead of erase do "myChild.erase()". Everything else I said holds true. Jun 5, 2011 at 20:03
  • You can also use FlexGlobals.topLevelApplication to access the the top level application and call the function that way; but it is also considered bad from an encapsulation stand point as it provides an external dependency to your component. Jun 5, 2011 at 20:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.