【问题标题】:passing an object to the constructor of a widget defined in uibinder将对象传递给 uibinder 中定义的小部件的构造函数
【发布时间】:2010-10-15 21:20:43
【问题描述】:

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

也就是说,我需要类似的东西

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 中引用已经存在的对象?

【问题讨论】:

    标签: gwt uibinder


    【解决方案1】:

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

    然后,我自己用 Java 构建了这个小部件,然后在父级上调用 initWidget

    例如:

    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)。这样您就可以将实例传递给您的小部件。

      使用&lt;ui:with&gt; 元素,您还可以将对象传递给小部件(前提是存在setter 方法)(如here 所述)。但是该对象将通过 GWT.create 实例化,我认为这不是您打算使用 eventBus 进行的。

      【讨论】:

      • 也是工厂方法的一个很好的例子:blog.jeffdouglas.com/2010/02/24/…
      • 我不想实例化一个新对象,因为它似乎需要一个工厂方法。这是一个不同的示例:假设我有一个名为 myString 的字符串,并且在 ui.xml 文件中我声明了一个 。如何指定
      • 传递一个字符串:用UiConstructor创建和注释你的ui类的构造函数,并在ui.xml文件中定义一个与constructors参数同名的属性。 public @UiConstructor MyWidget(String myString)&lt;my:MyWidget myString="foo" /&gt;.
      • 我又来了 :)。自从阅读了您的问题后,我很好奇您为什么要通过 ui.xml 传递 eventBus?如果您正在开发 MVP 风格的应用程序,我建议演示者是应该了解总线的类,在某些情况下可能也是小部件。但是为什么要进行演示呢?我相信你有你的理由,所以另一种可能性是将总线从一个小部件传递到另一个小部件。看看blog.jeffdouglas.com/2010/02/05/…
      • 感谢您的工作,但问题是我想传递一个已经存在的对象,而不是创建新的对象(如“foo.”)。
      猜你喜欢
      • 2011-10-09
      • 1970-01-01
      • 1970-01-01
      • 2014-06-04
      • 2023-03-30
      • 1970-01-01
      • 2012-07-09
      • 1970-01-01
      • 2011-11-28
      相关资源
      最近更新 更多