Search code examples
apache-flexcastingnullparent

Null cast between parent and child objects


I have a flex application with two objects: a parent widget (called an IBaseWidget) and a child widget (called a HelperWidget2). When the user clicks on a help link, a helper widget is loaded into the list of base widgets and then displayed for the user.

However, when I try to access this child widget by casting the base widget in the collection to the child widget type, the child widget returns null and I am unable to work with the widget.

The following snippet correctly returns the widget ID of the newly added widget and dispatches an event to load the widget:

var id:Number = WidgetManager.getInstance().getWidgetId("Helper");
ViewerContainer.dispatchEvent(new AppEvent(AppEvent.WIDGET_RUN, id, openQuickQueryCanvas));

Once the widget is loaded, a callback function called openQuickQueryCanvas() attempts to do another action with the helper widget:

private function openQuickQueryCanvas():void{
            var id:Number = WidgetManager.getInstance().getWidgetId("Helper");
            var bWidget:IBaseWidget = WidgetManager.getInstance().getWidget(id) as IBaseWidget;
            var helperWidget:HelperWidget2 = bWidget as HelperWidget2;
            if(helperWidget != null){
                helperWidget.quickQueryCanvas.dispatchEvent(new MouseEvent(MouseEvent.CLICK));//fire an event to open the quick query canvas
            }

        }

The problem is that helperWidget above always returns null, meaning the cast isn't successful. This doesn't make sense to me, because bWidget is of type HelperWidget2.

Any thoughts? I'm stumped...


Solution

  • First off, make sure that HelperWidget2 implements IBaseWidget like so

    public class HelperWidget2 implements IBaseWidget
    

    Second, I would suggest using the is keyword instead of casting and checking for null:

    private function openQuickQueryCanvas():void {
                    var id:Number = WidgetManager.getInstance().getWidgetId("Helper");
                    var bWidget:IBaseWidget = WidgetManager.getInstance().getWidget(id) as IBaseWidget;
    
                    if(bWidget is HelperWidget2)
                    {
                      HelperWidget2(bWidget).doWhatever();
                    }
    
                }