1

我想在单击不同按钮时调用不同的方法(在单个 GWT 事件处理程序类中)?它是这样的:

假设我的 UI 中有 3 个按钮:

  1. 按钮1
  2. 按钮2
  3. 按钮 3

而且,我为它们中的每一个都附加了相同的(单击)事件处理程序:ButtonClicker

在 OnClick() 方法中,我想调用与单击的按钮相对应的方法。这是一些示例代码,可以更好地说明我正在尝试做的事情:

public class ButtonClicker implements ClickHandler 
{
    public void onClick(ClickEvent event)
    {
        PushButton clickedButton = (PushButton) event.getSource();

        // I could call the corresponding method using if-else condition but I do not want to do that. 
        // Instead, I want some code here, may be using JSNI (using eval in some way) or something like that to call the corresponding method.
        ......      
    }

    private void Button1Click()
    {
        // Code to handle Button1 Click 
    }

    private void Button2Click()
    {
        // Code to handle Button2 Click
    }

    private void Button3Click()
    {
        // Code to handle Button3 Click
    }
}

提前致谢。

4

1 回答 1

2

我想你有很好的理由走这条错综复杂的路线,所以这里有一个建议,不包括判断:

JavaScriptObject map = createMap(this);

private static native JavaScriptObject createMap(ButtonClicker o) /*-{
   // Note: does not use $entry() as this will be called from GWT code
   return {
       "button1": function() { o.@foo.ButtonClicker::Button1Click()(); },
       "button2": function() { o.@foo.ButtonClicker::Button2Click()(); },
       "button3": function() { o.@foo.ButtonClicker::Button3Click()(); }
     };
}-*/;

private static native void call(JavaScriptObject map, String id) /*-{
  var fn = map[id];
  // TODO: add null-check / fallback behavior
  fn();
}-*/;

@Override
public void onClick(ClickEvent event) {
  call(map, ((UIObject) event.getSource()).getElement().getId());
}
于 2013-04-10T09:34:30.840 回答