2010-10-15 93 views
5

我试图将我的应用程序的EventBus传递给通过其构造函数在UiBinder中声明的小部件。我使用@UiConstructor注释来标记接受EventBus的构造函数,但我不知道如何从我的ui.xml代码实际引用对象。将对象传递给在uibinder中定义的小部件的构造函数

也就是说,我需要像

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> 

我传递一个静态值没有问题WidgetThatNeedsAnEventBus,我可以使用工厂方法创建一个新的EventBus对象。但我需要的是通过我的应用程序已有的EventBus。

有没有办法引用UiBinder中已经存在的对象?

回答

8

我最终的解决方案是在我需要用变量初始化的部件上使用@UiField(provided=true)

然后,我只是在父对象上调用initWidget之前,自己用Java构造了这个小部件。

例如:

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

我建议你使用工厂方法(描述为here)。这样你可以将一个实例传递给你的小部件。

使用<ui:with>元素,您还可以将对象传递给小部件(只要存在setter方法)(如文档here所述)。但该对象将通过GWT.create实例化,我认为这不是您打算用eventBus做的事情。

+0

也是一个很好的例子,为工厂方法:http://blog.jeffdouglas.com/2010/02/24/gwt-uibinder-passing-objects-to-widgets/ – z00bs 2010-10-15 22:33:30

+0

我不想实例化一个新的对象,因为它看起来像一个工厂方法所需要的。这里有一个不同的例子:假设我有一个名为myString的字符串,并且在一个ui.xml文件中,我声明了一个。我如何指定它应该使用Label(String)构造函数,并将myString的值传递给该构造函数? @UiField(provided = true)看起来很有前途,但我看不到如何将myString传递给构造函数。也许这对于UiBinder来说是不可能的? – 2010-10-16 13:46:13

+2

传递字符串:使用UiConstructor创建并注释您的ui类的构造函数,并在ui.xml文件中定义与构造函数参数完全相同的属性。 'public @UiConstructor MyWidget(String myString)'和''。 – z00bs 2010-10-16 16:33:46

相关问题