Search code examples
apache-flexcastingloadertypeerrorapplicationdomain

Type Coercion error when casting an object loaded in a different application domain


My application currently contains a number of Widgets that are managed by a Widget Manager. When the user clicks on a widget (e.g. a Helper widget), the Widget Manager loads the widget into a separate sibling application domain with the following line of code:

wgtInfo.load(null, null, null, moduleFactory); //wgtInfo = IModuleInfo

However, I am unable to use the widget's variables and functions later on. I attempt to find the Helper widget from the Widget Manager's list of widgets, and I do successfully. But when I try to caste the Helper Widget from type IBaseWidget (the interface all widgets share) to type HelperWidget, I receive the following error:

TypeError: Error #1034: Type Coercion failed.....

This is because the application domain of the class trying to use the Helper widget is different from the application domain of the Helper Widget. I tried to fix this by loading all widgets into the same application domain as the loader:

wgtInfo.load(ApplicationDomain.currentDomain, null, null, moduleFactory);

I now get the following error whenever I attempt to load the Helper widget:

TypeError: Error #1009: Cannot access a property or method of a null object reference.

How can I load my Helper widget into a common application domain that is accessible by the other widgets?


Solution

  • After trying a number of solutions unsuccessfully (including the other responses on this page), I resorted to another, event-driven, solution.

    I ended up dispatching a custom event to notify my other widgets when the Helper widget had completed loading:

    (HelperWidget.mxml)

    ViewerContainer.addEventListener(AppEvent.WIDGET_OPEN_TAB, widgetOpenTabHandler); //listen for other widgets to open a tab within the Helper Widget
    ViewerContainer.dispatchEvent(new AppEvent(AppEvent.WIDGET_READY_OPEN_TAB)); //notify other widgets that loading is complete
    

    My other widgets listen for this event to fire, and upon completion, dispatch another event (AppEvent.WIDGET_OPEN_TAB) to perform a function within the Helper widget.