2011-05-17 67 views
47

我還不熟悉GWT,想知道如何使用EventBus或者是否有更好的解決方案通過項目發送事件。如何使用GWT EventBus

控件1有一個按鈕。 Widget 2有一個標籤,當我按下按鈕時該標籤應該改變。 這些微件在DockLayout:

RootLayoutPanel rootLayoutPanel = RootLayoutPanel.get(); 
    DockLayoutPanel dock = new DockLayoutPanel(Unit.EM); 

    dock.addWest(new Widget1(), 10); 
    dock.add(new Widget2()); 

    rootLayoutPanel.add(dock); 

我在小部件1

@UiHandler("button") 
void handleClickAlert(ClickEvent e) { 
    //fireEvent(e); 
} 

希望有人能幫助我宣佈一個handleClickAlert。謝謝!

回答

104

當您將項目劃分爲邏輯部分(例如MVP)時,有時需要進行通信。典型的通信是發送狀態更改,例如:

  • 用戶已登錄/失蹤。
  • 用戶直接通過URL導航到頁面,因此需要更新菜單。

在這些情況下使用事件總線非常合乎邏輯。

要使用它,您可以爲每個應用程序實例化一個EventBus,然後由所有其他類使用它。要實現這一點,請使用靜態字段,工廠或依賴注入(GWT情況下的GIN)。與你自己的事件類型

例子:

public class AppUtils{ 

    public static EventBus EVENT_BUS = GWT.create(SimpleEventBus.class); 
} 

通常情況下,你還需要創建自己的事件類型和處理程序:

public class AuthenticationEvent extends GwtEvent<AuthenticationEventHandler> { 

public static Type<AuthenticationEventHandler> TYPE = new Type<AuthenticationEventHandler>(); 

    @Override 
public Type<AuthenticationEventHandler> getAssociatedType() { 
    return TYPE; 
} 

@Override 
protected void dispatch(AuthenticationEventHandler handler) { 
    handler.onAuthenticationChanged(this); 
} 
} 

和處理程序:

public interface AuthenticationEventHandler extends EventHandler { 
    void onAuthenticationChanged(AuthenticationEvent authenticationEvent); 
} 

然後你這樣使用它:

AppUtils.EVENT_BUS.addHandler(AuthenticationEvent.TYPE, new AuthenticationEventHandler()  { 
     @Override 
     public void onAuthenticationChanged(AuthenticationEvent authenticationEvent) { 
      // authentication changed - do something 
     } 
    }); 

,並觸發事件:

AppUtils.EVENT_BUS.fireEvent(new AuthenticationEvent()); 
+0

感謝。這對我很有幫助! – Mark 2011-05-17 12:16:13

+0

發射事件時,我怎麼能發送一個對象?在我的情況下,我需要發送一個包含我的用戶信息的類。 – elvispt 2011-08-18 20:18:17

+8

你可以在你的自定義事件中有一個字段,並通過構造函數設置它,即'new AuthenticationEvent(someObject)' – 2011-08-18 21:14:39