5 Feb 2012

Handling key modifiers for client events

In this post I'm going to show how we can check and use the key modifier flags for client components events. The flags indicate which combination of CTRL, SHIFT and ALT keys was pressed. Let's say we have some commandButton and we need to handle if Shift key is hold down on the mouse click event.
We have the following task flow:

If Shift key is hold, the button will produce *Clone action, if not the button will produce *Create  action. In our MainView we have a button:

        <af:commandButton text="commandButton 1" id="cb1">                          
          <af:clientListener method="handleBtnClick" type="click"/>
          <af:serverListener type="hanldeAction"
                             method="#{MainHandlerBean.actionEvent}"/>
        </af:commandButton>

It has clientListener pointing to JS function handleBtnClick and it has serverListner pointing to the backing bean method actionEvent. JS function is triggered on click event and it looks as following:

           function handleBtnClick(evt) {
              //evt is AdfDomUIInputEvent
              //we need to get native DOM event
              //because it has modifiers properties
              
              var nativeEvent = evt.getNativeEvent();
              
              //Invoking server listener and passing if Shift key is pressed
              //as a parameter to the MainHandlerBean.actionEvent method.
              //In our case we check shiftKey property
              //Actually it can be shiftKey, ctrlKey, altKey
              
              AdfCustomEvent.queue(evt.getSource(), "hanldeAction", 
                                  {shiftKey:nativeEvent.shiftKey} ,false); 
              event.cancel();
           }

The backing bean method looks like this:
    public void actionEvent(ClientEvent clientEvent) {
        //Checking the parameter passed from the client
        if ((Boolean) clientEvent.getParameters().get("shiftKey"))
            HandleNavigation("*Clone");
        else
            HandleNavigation("*Create");
        
    }
    
    public static void HandleNavigation(String outcome)
    {
      FacesContext context = FacesContext.getCurrentInstance();
      NavigationHandler nh = context.getApplication().getNavigationHandler();
      nh.handleNavigation(context, "", outcome);
    }
        
That's it.

No comments:

Post a Comment

Post Comment