passing an object to the constructor of a widget defined in uibinder

旧时模样 提交于 2019-12-10 14:41:12

问题


I'm trying to pass my app's EventBus to a widget declared in a UiBinder via its constructor. I'm using the @UiConstructor annotation to mark a constructor that accepts the EventBus, but I don't know how to actually reference the object from my ui.xml code.

That is, I need something like

WidgetThatNeedsAnEventBus.java

public class WidgetThatNeedsAnEventBus extends Composite
{
    private EventBus eventBus;

    @UiConstructor
    public WidgetThatNeedsAnEventBus(EventBus eventBus)
    {
        this.eventBus = eventBus;
    }
}

TheUiBinderThatWillDeclareAWTNAEB.ui.xml

<g:HTMLPanel>
    <c:WidgetThatNeedsAnEventBus eventBus=_I_need_some_way_to_specify_my_apps_event_bus_ />
</g:HTMLPanel>

I have no problem passing a static value to the WidgetThatNeedsAnEventBus, and I can use a factory method to create a new EventBus object. But what I need is to pass my app's already-existing EventBus.

Is there a way to refer to already-existing objects in a UiBinder?


回答1:


My eventual solution was to use @UiField(provided=true) on the widget I needed to initialize with a variable.

Then, I just constructed the widget myself in Java, before calling initWidget on the parent.

For example:

public class ParentWidget extends Composite
{
    @UiField(provided=true)
    protected ChildWidget child;

    public ParentWidget(Object theObjectIWantToPass)
    {
        child = new ChildWidget(theObjectIWantToPass);  //_before_ initWidget
        initWidget(uiBinder.create(this));

        //proceed with normal initialization!
    }
}



回答2:


I'd suggest you use a factory method (described here). This way you can pass an instance to your widget.

With the <ui:with> element you can also pass objects to widgets (provided a setter method exists) (as documented here). But the object will be instantiated via GWT.createwhich I think is not was you intend doing with the eventBus.



来源:https://stackoverflow.com/questions/3946242/passing-an-object-to-the-constructor-of-a-widget-defined-in-uibinder

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!