Search code examples
javagwtgwtquery

Defining common handler for click elements in GWTQuery


In my GWTQuery project, I have a situation where there are 4 custom drop-down menus. Whenever a user changes any of the current menu choice, an AJAX request is made with the values of the 4 menus (one of which is the newly changed value of that menu). Since all the 4 menus trigger similar request, I though that I will write a common class to handle the AJAX request, then let the clickhandlers extend that class.

But then, the menus being dynamically generated, I have to resort to GWTQuery's live method. And that takes a variable of type Function as parameter. Since it already extends Function, I can't make it extend my Ajax handler class as well. So how do I do it? Something like this is what I am looking for:

class f extends Funnction, AJAX_Handler {
 public boolean f(Event e) {
  ...
  return true;
  }
 public void request(int i1,int i2,int i3,int i4) {
  //for handling the request, defined in the AJAX_Handler class
  ...
  }
 }

One thing, defining a generic handler for all 4 menus which contains the AJAX_handler functions, then detecting which menu is the current handler referring to is a no-no. The AJAX_handler class has to be a separate one.


Solution

  • Define interfaces instead.

     public interface AJAX_Handler
     {
        public void request(int i1,int i2,int i3,int i4);
    
     }
    

    Then in your actual class implement the defined interface.

     class f extends Funnction implements AJAX_Handler
     {
       public boolean f(Event e) {
          ...
        return true;
        }
       public void request(int i1,int i2,int i3,int i4) {
       //for handling the request, defined in the AJAX_Handler class
        ...
        }
      }
    

    [EDIT] Given that you need to keep the functionality in the same place. I think the simplest fix would be to define the AJAX_Handler interface then have an implemented class. For example:

     public class AJAX_HandlerImpl implements AJAX_Handler
     {
        public void request(int i1,int i2,int i3,int i4){
             //do whats necessary
         }
     }
    

    Then use composition in your f class. Something like:

     class f extends Funnction implements AJAX_Handler
     {
       private AJAX_HandlerImpl impl = new AJAX_HandlerImpl();
    
       public boolean f(Event e) {
          ...
        return true;
        }
    
       public void request(int i1,int i2,int i3,int i4) {
              impl.request(i1,i2,i3,i4);
        }
      }